Quick Answer
Passing functions as parameters and returning functions
Understanding the Issue
Kotlin treats functions as first-class citizens. Higher-order functions (HOFs) are functions that take other functions as parameters or return them. Lambdas provide concise syntax for function literals.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Verbose anonymous class
view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
doSomething()
}
})
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution: Lambda syntax
view.setOnClickListener { doSomething() }
// Custom HOF example:
fun measureTime(block: () -> Unit): Long {
val start = System.currentTimeMillis()
block()
return System.currentTimeMillis() - start
}
Key Takeaways
Lambdas and HOFs enable concise functional-style programming.