Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about lambda and function

Tags:

lambda

kotlin

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

like image 464
V Adhi Pragantha Avatar asked Dec 01 '25 01:12

V Adhi Pragantha


1 Answers

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
like image 53
EpicPandaForce Avatar answered Dec 05 '25 06:12

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!