0

Reading about higher order functions in Kotlin, I see a syntax for passing a function implementation ("inline") like the following one:

calculate(4, 5) { a, b -> a * b }

The a, b -> a * b part is actually a function passed to a function. Full snippet:

fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {  // 1
    return operation(x, y)                                          // 2
}

fun sum(x: Int, y: Int) = x + y                                     // 3

fun main() {
    val sumResult = calculate(4, 5, ::sum)                          // 4
    val mulResult = calculate(4, 5) { a, b -> a * b }               // 5
    println("sumResult $sumResult, mulResult $mulResult")
}

Consider having a function that receives 2 functions, e.g.

fun calculate2(x: Int, y: Int, operation: (Int, Int) -> Int, operation2: (Int, Int) -> Int): Int {
    //...
}

How do I pass it 2 function implementations - "inline" (without first declaring the functions)?

Trying to do like the following gives me a compilation error:

calculate(4, 5) { a, b -> a * b} {a, b -> a + b }

Screencap: enter image description here

1 Answer 1

3
calculate(4, 5, { a, b -> a * b }, { a, b -> a + b })

or

calculate(4, 5, { a, b -> a * b }) { a, b -> a + b }
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.