fun main() {
// Lambda assigned to a val
val square: (Int) -> Int = { n -> n * n }
println(square(5)) // 25
// Implicit `it` for single-arg lambdas
val nums = listOf(1, 2, 3, 4, 5)
println(nums.filter { it > 2 }) // [3, 4, 5]
println(nums.map { it * it }) // [1, 4, 9, 16, 25]
// Trailing-lambda syntax — last arg can move outside the parens
nums.forEach { println(it) }
// equivalent to: nums.forEach({ println(it) })
// Higher-order — function that takes a function
fun applyTwice(n: Int, f: (Int) -> Int): Int = f(f(n))
println(applyTwice(3) { it + 10 }) // 23
// Function references with ::
fun double(n: Int) = n * 2
println(nums.map(::double)) // [2, 4, 6, 8, 10]
}
Create a free account and build your private vault. Share publicly whenever you want.