Careeroza
Trailing Lambdas and Function References
Trailing Lambda Syntax
If the last parameter is a function, the lambda can go outside the parentheses. If it is the only argument, the parentheses can be dropped. This is why Kotlin code (and Jetpack Compose) looks like Column { ... }.
Example
fun measure(label: String, block: () -> Unit) {
println("Start $label")
block()
println("End $label")
}
fun main() {
measure("sync", { println(" working (inside parentheses)") })
measure("sync") { println(" working (trailing lambda)") }
listOf(1, 2, 3).forEach { print("$it ") }
println()
}Output
Start sync working (inside parentheses) End sync Start sync working (trailing lambda) End sync 1 2 3
Function References (::)
::functionName turns an existing function into a value, so you can pass it where a lambda is expected. It also works for constructors (::User) and members (String::length).
Example
data class User(val name: String)
fun isAdult(age: Int) = age >= 18
fun main() {
val ages = listOf(12, 25, 17, 40)
println(ages.filter(::isAdult))
println(listOf("asha", "ravi").map(String::uppercase))
println(listOf("Asha", "Ravi").map(::User))
listOf("done").forEach(::println)
}Output
[25, 40] [ASHA, RAVI] [User(name=Asha), User(name=Ravi)] done