Predict the output
What does this print?
fun interface Formatter {
fun format(x: Int): String
}
fun main() {
val twice: (Int) -> Int = { it * 2 }
val f = Formatter { "#$it" }
println(f.format(twice(21)))
println(buildString { append("a"); append("b") })
}Hint 1 of 1
What does twice(21) return?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A #42, then ab
Correct. The lambda doubles 21, the fun interface formats it, and buildString uses a receiver lambda.
Why not the others?
- B #21, then ab. twice(21) runs first and gives 42.
- C 42, then ab. The formatter adds the # prefix.
- D It doesn't compile: interfaces can't be created from lambdas. A fun interface can.