Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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 Jun 3 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 Jun 3 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 Jun 3 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 Jun 3 by avibootz

Related questions

4 answers 145 views
4 answers 159 views
5 answers 217 views
4 answers 161 views
3 answers 138 views
...