How to use closure in Kotlin

4 Answers

0 votes
fun main() {
    val x: Int = 10
    val y: Int = 20

    // This lambda captures x and y from the surrounding scope.
    val add: () -> Int = { x + y }

    val result: Int = add()

    println(result)
}


/*
run:

30

*/

 



answered 1 day ago by avibootz
0 votes
// Closures capture variables by reference

fun main() {
    var counter: Int = 0

    // Closure capturing and modifying "counter"
    val inc: () -> Unit = {
        counter++
    }

    inc()
    inc()

    println(counter)
}


/*
run:

2

*/

 



answered 1 day ago by avibootz
0 votes
// Closures with parameters

fun main() {
    val factor: Int = 3

    // Closure capturing "factor"
    val multiply: (Int, Int) -> Int = { a: Int, b: Int ->
        (a + b) * factor
    }

    println(multiply(5, 5))
}


/*
run:

30

*/

 



answered 1 day ago by avibootz
0 votes
// Closures inside collection operations

fun main() {
    val nums: List<Int> = listOf(1, 2, 3)
    val factor: Int = 2

    // map uses a closure that captures "factor"
    val doubled: List<Int> = nums.map { n: Int -> n * factor }

    println(doubled)
}



/*
run:

[2, 4, 6]

*/

 



answered 1 day ago by avibootz

Related questions

4 answers 16 views
4 answers 19 views
5 answers 24 views
4 answers 20 views
3 answers 22 views
...