Hi all, long time Kotlin user here. I was thinking...
# language-proposals
o
Hi all, long time Kotlin user here. I was thinking of improving the syntax for one-liner method calls inside lambdas. Imagine this code:
names.groupBy { it.length }
, one could use
names.groupBy(String::length)
, but it's kinda cumbersome in many cases, especially when chained, and it's unclear what happens when the method has arity of 1.
names.groupBy(::length)
would be shorter, but
::length
is evaluated in the current lexical scope. How about something like
names.groupBy(.length)
? Scala has
names.groupBy(_.length)
, Ruby has `Symbol#to_proc`:
names.group_by(&:length)
. What do you guys think?
👍 1
v
Did I understand you correctly that this will saving typing 2 characters in
it
, or even only one when compare to
_.length
?
o
I don't think
_.length
would work in Kotlin
so yeah, it's about saving the
it.
part and the curly braces
I know, I'm spoiled 😛
I'm not sure about performance, though
maybe with
{ it.length }
, the generated bytecode needs to evaluate the lambda on every iteration, whereas with
(.length)
it could do some optimizations
k
Try looking at some generated bytecode to see if there's really a difference.
o
Any tips on how I could do that? I'll give it a try
BTW that
.something
shorthand syntax could also be used for accessing enums, similar to Swift
k
Tools > Kotlin > Show bytecode and if you want Decompile to Java.
o
nice, thanks!
v
You are not even saving the braces characters because you replace
()
with
{}
.
o
true, but it just reads better somehow to me
a
Your concern here seems to be just the curly braces. It’s going to be really confusing to new users when parentheses can now refer to lambdas based on the contents inside. You can also solve this yourself if it’s just character based:
Copy code
public inline fun <T, K> Array<out T>.groupBy(keySelector: T.() -> K) = groupBy{ it.keySelector() }
Though this naturally hinders readability and is why it wasn’t written this way in the first place.
k
That won't help the curly braces go away though?
a
I said if it was just character based, in that this removes
it
👍 1
(as in character count. bad wording)
o
thanks for the reply, Allan
you're right about readability, I was more thinking of a short-hand syntax for a method reference on
it