WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 12 of 100

What are lambdas in Kotlin? How are they used in higher-order functions?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, a lambda expression is a function literal that can be used as an anonymous function. A lambda expression is defined using curly braces containing the function body, and the input parameters (if any) are listed before the function body, separated by a arrow ->. For example:

val square: (Int) -> Int = { x -> x * x }

This lambda expression defines a function that takes an Int as input and returns the square of that number as an Int. The variable ‘square‘ has a functional type that represents a function of one Int input and one Int output.

Lambdas are often used in Kotlin in conjunction with higher-order functions. A higher-order function is a function that takes one or more functions as input and/or returns a function as output. For example:

fun applyOperation(x: Int, operation: (Int) -> Int): Int {
    return operation(x)
}

val result = applyOperation(5, { x -> x * x })

//result = 25

In this example, the ‘applyOperation‘ function takes two arguments: an Int ‘x‘ and a function of type ‘(Int) -> Int‘ called ‘operation‘. The function ‘applyOperation‘ simply applies the ‘operation‘ function to the input ‘x‘ argument and returns the result.

The variable ‘result‘ is assigned the value returned by the call to ‘applyOperation‘ with the input arguments ‘5‘ and a lambda expression that defines the ‘operation‘ function. In this case, the lambda expression is ‘ x -> x * x ‘, which is the same lambda expression we defined earlier to represent the ‘square‘ function.

Lambdas make it easy to define and pass functions around as first-class objects in Kotlin, allowing for greater flexibility and modularity in code design.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics