Functions are first-class values in Kotlin—lambdas pass behavior to APIs like map and filter. Syntax is leaner than anonymous inner classes in Java and closer to JavaScript arrow functions.
Lambda syntax
val double: (Int) -> Int = { it * 2 }
list.filter { it > 0 }
When a lambda is the last argument, trailing lambda syntax moves it outside parentheses. Single-parameter lambdas can use it.
Higher-order functions
Functions accepting or returning functions enable reusable patterns—e.g. fun retry(times: Int, block: () -> Unit).
Important interview questions and answers
- Q: What is it?
A: Implicit name for the single lambda parameter when omitted. - Q: Lambda vs anonymous object?
A: Lambdas compile to invokedynamic on JVM; objects needed when implementing multiple methods or carrying state.
Self-check
- How do you declare a function type (Int) -> String?
- When can you use trailing lambda syntax?
Tip: Use trailing lambda syntax: list.filter { it > 0 } when the last arg is a function.
Interview prep
- it keyword?
Implicit name for single lambda parameter.
- Trailing lambda?
Last function arg can move outside parentheses.