I just noticed something interesting when testing a code and I would like more explanation. Why functions have the priority over lambdas when they are in the same scope ?
For example :
fun sum(x: Int, y:Int) = x + y
val sum = { x: Int, y: Int -> x + y }
// here, the compiler use the fonction (first line) and not the lambda
println(sum(1, 2))
In this case, I use invoke()
to call the lambda instead of the function.
Higher-Order Function – In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas.
Variable number of arguments (varargs)Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.
The Overload
resolution section of kotlin language specification does touch on this, it states
When calculating overload candidate sets, member callables produce the following separate sets (ordered by higher priority first):
Member function-like callables; Member property-like callables.
but the specification still seems to be a work in progress as it contains a lot of TODO's, one specific TODO that would be relevant to your question is in the Callable references section
TODO(We might get new ambiguity between props and funs with the same name)
So it seems to get a definite answer, you will have to wait until the language specification matures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With