2

Suppose I have high order function that accepts a lambda as a parameter like this:

fun getNum(op: () -> Int) = op()

And a function that returns a number:

fun getTen() = 10

In the main function I can call the getNum() function like this

fun main(args: Array<String>){
    val x = 50
    val a = getNum(::getTen)    // a == 10
    val b = getNum{x}           // this works and b == 50
}

Why does passing a varibale instead of lambda works? Any idea? Thanks.

1 Answer 1

3

In Kotlin, the last or the single expression in a lambda is the return value.

In the getNum { x } expression, { x } is a lambda with a single expression x in it, which is thus considered the return value, so when the lambda is invoked, it only evaluates x captured in the closure and returns its value back to getNum.

The getNum(::getTen) call is, in turn, the usage of a callable reference (it is distinguishable by the :: sign), which can be passed as a value of the functional type () -> Int just the same as if it would be getNum { getTen() }.

See: Lambda Expressions and Anonymous Functions in the language reference.

Sign up to request clarification or add additional context in comments.

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.