So I just playing around with kotlin and can't get around my head about this.
fun itsAfunction() = 10
fun check(function:()->Int):Int{
return function() + 9
}
val result = check(itsAfunction)
why I can not pass a function inside the function check?
if I did something like this, this will be accepted
val result = check({itsAfunction})
the question is what is the difference between function and lambda? I always tough both are the same but in this case it is not.
thank you
If you want to pass a function of a class as an argument, you should use function reference (also called callable reference / function literal).
val result = check(::itsAfunction)
But the following would be equivalent (afaik):
val result = check { itsAfunction() } //<-- enclosing () is omitted because trailing lambda
If you make the check function be inline:
inline fun check(func: () - > Int) = func() + 9
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