Lambdas Workbook (Part 4): References, Returns, and Anonymous Functions
Practice problems for Lambdas, Sharpened: References, Returns, and Anonymous Functions. 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.
the four kinds of reference
1. A member reference
Uppercase each of words using a member reference instead of the lambda { it.uppercase() }.
Show answer Hide answer
words.map(String::uppercase) 2. A top-level function reference
Given fun isEven(n: Int) = n % 2 == 0, filter nums to its even elements using a reference.
Show answer Hide answer
nums.filter(::isEven) 3. A bound reference
Given a logger with fun log(m: String), print each message in messages using a bound reference.
Show answer Hide answer
messages.forEach(logger::log) 4. A constructor reference
Given class User(val id: Int) and ids: List<Int>, build a User for each id with a constructor reference.
Show answer Hide answer
ids.map(::User) 5. Replace a forwarding lambda
Replace the lambda in words.map { it.trim() } with a reference.
Show answer Hide answer
words.map(String::trim) returns and labels
6. A non-local return
Write firstEven(numbers: List<Int>): Int? that uses forEach and a plain return to return the first even number, or null.
Show answer Hide answer
fun firstEven(numbers: List<Int>): Int? {
numbers.forEach { if (it % 2 == 0) return it }
return null
}A plain return exits firstEven, not just the lambda.
7. Skip with a labelled return
Using forEach, print every element of nums except negatives — skip a negative with a labelled return.
Show answer Hide answer
nums.forEach {
if (it < 0) return@forEach
println(it)
} 8. The two returns, side by side
Write two forEach lambdas over nums: one that exits the enclosing function on the first zero, and one that merely skips zeros.
Show answer Hide answer
nums.forEach { if (it == 0) return } // exits the whole function
nums.forEach { if (it == 0) return@forEach; println(it) } // skips this element anonymous functions
9. Rewrite a lambda as an anonymous function
Rewrite { n: Int -> n * 2 } as an anonymous function.
Show answer Hide answer
fun(n: Int): Int { return n * 2 }Inside an anonymous function, a plain return returns from it — the normal rules.
10. Pass an anonymous function
Pass an anonymous function to filter that keeps positive numbers.
Show answer Hide answer
nums.filter(fun(n: Int): Boolean { return n > 0 }) 11. A bound reference to a method with a result
Given val parser = Parser() with fun parse(s: String): Int, map lines through parser.parse using a bound reference.
Show answer Hide answer
lines.map(parser::parse) 12. A constructor reference for a data class
Given data class Point(val x: Int) and xs: List<Int>, build points using ::Point.
Show answer Hide answer
xs.map(::Point) Back to the lesson, References, Returns, and Anonymous Functions, or on to part five: why lambdas are free.
Comments