Consider the following Kotlin code snippet:
val numbers = listOf(1, 2, 3)
numbers.forEach { print(it * 2) }What will be printed when this code runs?
val numbers = listOf(1, 2, 3) numbers.forEach { print(it * 2) }
Remember that forEach applies the given action to each element in the list.
The forEach function runs the lambda for each element. Here, it prints each number multiplied by 2 without spaces, so the output is 246.
Choose the correct statement about the forEach function in Kotlin collections.
Think about what forEach does with the elements and its return type.
forEach applies the given action to each element and returns Unit. It does not transform or return a new collection.
Examine the code below:
val items = listOf("a", "b", "c")
items.forEach { it = it.uppercase() }What error will this code produce?
val items = listOf("a", "b", "c") items.forEach { it = it.uppercase() }
Consider whether the lambda parameter it can be reassigned.
The lambda parameter it is read-only (val). Trying to assign to it causes a compilation error.
Consider this Kotlin code:
val list = listOf("x", "y", "z")
list.forEachIndexed { index, value -> print("$index$value") }What will be printed?
val list = listOf("x", "y", "z") list.forEachIndexed { index, value -> print("$index$value") }
Remember forEachIndexed provides both index and element.
The code prints the index followed by the element for each item, resulting in 0x1y2z.
Which of the following Kotlin code snippets will cause a compilation error?
Check the lambda syntax in Kotlin carefully.
Kotlin does not use the arrow syntax it -> for lambdas. The correct syntax uses curly braces with parameters before the arrow or implicit it.