Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why functions have priority over the Property-like callables in the same scope?

Tags:

lambda

kotlin

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.

like image 497
Jéwôm' Avatar asked Feb 10 '20 13:02

Jéwôm'


People also ask

What are higher order functions in Kotlin?

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.

How do you use Vararg Kotlin?

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.


1 Answers

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.

like image 98
mightyWOZ Avatar answered Sep 28 '22 07:09

mightyWOZ