Lambdas Workbook (Part 1): The Basics


Practice problems for A Kotlin Lambda Is a Value You Can Pass Around. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.

defining and calling

1. Store and run

Store a lambda that prints "hi" in a variable greet, then run it.

Show answer Hide answer
val greet = { println("hi") }
greet()

2. Defining isn’t running

Given val greet = { println("hi") }, write the single line that actually runs the code inside.

Show answer Hide answer
greet()

Defining the lambda prints nothing; only calling it does.

3. One parameter

Write a lambda welcome that takes a String name and prints Welcome, <name>, then call it with "Ada".

Show answer Hide answer
val welcome = { name: String -> println("Welcome, $name") }
welcome("Ada")

results

4. Return a number

Write a lambda square that returns its Int argument multiplied by itself.

Show answer Hide answer
val square = { x: Int -> x * x }

The last expression in the body is the result — no return.

5. Return a String

Write a lambda shout that returns its String argument uppercased with a ! appended.

Show answer Hide answer
val shout = { s: String -> s.uppercase() + "!" }

6. Return a Boolean

Write a lambda isAdult that returns whether an Int age is at least 18.

Show answer Hide answer
val isAdult = { age: Int -> age >= 18 }

7. A multi-line body

Write a lambda grade taking an Int score: on the first line compute "pass" or "fail", and make "Result: <that>" the last line.

Show answer Hide answer
val grade = { score: Int ->
    val outcome = if (score >= 50) "pass" else "fail"
    "Result: $outcome"
}

function types and it

8. Read a type

Write the function type of a lambda that takes two Ints and returns an Int.

Show answer Hide answer
(Int, Int) -> Int

9. Declare with an explicit type

Declare val add with type (Int, Int) -> Int whose body adds its two arguments.

Show answer Hide answer
val add: (Int, Int) -> Int = { a, b -> a + b }

With the type on the left, you can drop the parameter types inside the braces.

10. The it shortcut

Rewrite the lambda { n: Int -> n > 0 } using the implicit single-parameter name.

Show answer Hide answer
{ it > 0 }

11. No input, no output

Write a lambda of type () -> Unit that prints tick.

Show answer Hide answer
val tick: () -> Unit = { println("tick") }

12. Drop the parameter type

Given val negate: (Boolean) -> Boolean = { ... }, supply a body that flips the boolean — without writing the parameter’s type.

Show answer Hide answer
val negate: (Boolean) -> Boolean = { b -> !b }

Back to the lesson, A Kotlin Lambda Is a Value, or on to part two: lambdas at work.

Comments