Is there somewhere that details the differences between a top-level function variable, and a top-level function, and what considerations there are in choosing one over the other?
val topLevelFunctionVariable: (String) -> Int = { it.length }
fun topLevelFunction(value: String): Int = value.length
m
Marcelo
09/06/2021, 8:44 PM
The real difference in this case, you can use into some Class as a client callback function for example.
t
Tobias Berger
09/06/2021, 8:54 PM
there is also the slight difference that - at least when running on jvm - your function variable will store the lambda wrapped in an object. This object is not needed for the top level function.
Because you can use method references, you can even use the top level function as a parameter for higher order functions.
In general I would suggest sticking to functions instead of variables holding lambdas. They may be the way to go in JS/TS, but in my experience are very uncommon in Kotlin.
➕ 1
c
CLOVIS
09/07/2021, 9:52 AM
@Tobias Berger that is true, however for top-level declarations, that additional object hardly makes any difference.