User-defined or pre-set names for parameters inside a lambda


#1

My proposal is allow lambda parameters to be “named” like regular functions. This can give the end-user of the lambda a bit better of an idea of which parameter should do what, as long as the parameter name is accurate to what it is. It can get particularly annoying working with multiple-parameter lambdas and having to re-type the parameter names every time the lambda has more than 1 parameter. This is meant at increasing developer efficiency, they no longer have to write X parameter names every time they want to go inside multi-parameter lambdas.

fun doThing(block: (intValue1: Int, intValue2: Int, stringValue: String) -> Unit) { ... }

// instead of this
doThing { intValue1, intValue2, stringValue ->
    println("$stringValue ${intValue1 * intValue2}")
}

//do this
doThing { // Here would be a type hint box in the IDE with the names and types of parameters
    println("$stringValue ${intValue * longValue}")
}

#2

This can already be achieved via extension lambdas. It is a bit boilerplate though.


#3

It CAN achieve the same thing, and I do use this sort of structure in some places throughout my code. Though it is important to note when bringing up boilerplate like this is that one of the big selling points of Kotlin is reduced boilerplate!


#4

I agree. However a good alternative to your suggestion would be to introduce syntactic sugar for the already existing means.


#5

i figured thats essientially what it would be in the end to the compiler is syntactic sugar


#6

The original version is IMO much more readable and IDE will autocomplete parameter names anyway.

A lot of these syntactic shortcuts look good on paper, but hurt readability in the long run. It is easy to mistake more typing for boilerplate, but as the saying goes - code is written once, but read many times.


#7

Yes. In the first version, it’s much easier to see where the variables intValue and longValue come from. And you aren’t always reading code from the IDE, often you look at git diffs or code blocks pasted to bug trackers and so on.


#8

This is an incompatible change

fun doThing(block: (stringValue: String) -> Unit) { block("bye") }

val stringValue = "hello"
doThing {
    println(stringValue)
}