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

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}")
}
1 Like

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

2 Likes

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!

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

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

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.

6 Likes

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.

This is an incompatible change

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

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