How to use an anonymous function in Kotlin

3 Answers

0 votes
// Anonymous function = A function with no identifier.

fun main() {
    // Anonymous function (lambda) that takes two Ints and returns their sum.
    // { a, b -> a + b }  ← Kotlin’s concise lambda syntax.
    val add: (Int, Int) -> Int = { a, b -> a + b }

    // Use the anonymous function
    val result = add(10, 20)

    println(result)
}


/*
run:

30

*/

 



answered 11 hours ago by avibootz
edited 11 hours ago by avibootz
0 votes
fun main() {
    val add = { a: Int, b: Int -> a + b }
    
    println(add(10, 20))
}


/*
run:

30

*/

 



answered 11 hours ago by avibootz
0 votes
fun main() {
    println({ a: Int, b: Int -> a + b }(10, 20))
}


/*
run:

30

*/

 



answered 11 hours ago by avibootz
...