What if one small trick could save you from repeating code and bugs when handling many buttons or actions?
Why Closures and variable capture in Kotlin? - Purpose & Use Cases
Imagine you want to create several buttons in an app, each showing a different message when clicked. You try to write separate code for each button manually, repeating yourself over and over.
This manual way is slow and boring. If you want to change the message, you must update every button's code. It's easy to make mistakes, like showing the wrong message or forgetting to update one button.
Closures let you write one piece of code that remembers the message for each button. You create a function that captures the message variable, so each button keeps its own message without extra code.
val buttons = listOf(button1, button2)
button1.setOnClickListener { println("Hello") }
button2.setOnClickListener { println("Bye") }val messages = listOf("Hello", "Bye") val buttons = listOf(button1, button2) buttons.forEachIndexed { i, btn -> btn.setOnClickListener { println(messages[i]) } }
Closures make your code simpler and smarter by remembering values automatically, so you can create flexible and reusable functions easily.
In a shopping app, closures help each product button remember its price and name, so clicking any button shows the right details without writing separate code for each product.
Manual repetition is slow and error-prone.
Closures capture variables to keep data inside functions.
This leads to cleaner, reusable, and easier-to-maintain code.