3

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

1
  • If it's giving you an error, it would help if you state what the error is. One has to infer from your question that the first example of code generates an error. Commented Jul 15, 2018 at 15:57

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

When using Jetpack Compose, you should always prefer the first version. The second version with check {} can cause performance issues.
1

function in Kotlin is named or declared but Lambda is an undeclared or anonymous function

Named function cannot be passed as parameter to a function.

your above need can be solved by creating a variable of function type and pass as a parameter in function call

val itsAfunction: () -> Int = { -> 10 }

fun check(function:()->Int):Int{
    return function() + 9
}

val result = check(itsAfunction)
println("result ${result}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.