Consider the following Kotlin code that transforms a map. What will be printed?
val original = mapOf("a" to 1, "b" to 2, "c" to 3) val transformed = original.mapValues { it.value * 2 } println(transformed)
mapValues applies a transformation only to the values, keeping keys the same.
The mapValues function creates a new map with the same keys but transforms each value by multiplying it by 2. So 1 becomes 2, 2 becomes 4, and 3 becomes 6.
Given this Kotlin code, what is the output?
val numbers = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four") val filtered = numbers.filterKeys { it % 2 == 0 }.mapValues { it.value.uppercase() } println(filtered)
filterKeys keeps only keys that satisfy the condition, then mapValues transforms the values.
The filterKeys keeps only keys 2 and 4 (even numbers). Then mapValues converts their values to uppercase strings.
Look at this Kotlin code snippet. It tries to create a new map with values doubled only if the value is greater than 2. Why does it fail to compile?
val data = mapOf(1 to 1, 2 to 3, 3 to 5) val result = data.mapValues { if (it.value > 2) it.value * 2 } println(result)
Consider what happens when the if condition is false inside the lambda.
The lambda returns a value only when it.value > 2. When false, it returns Unit implicitly, causing a type mismatch because mapValues expects a consistent return type.
Choose the Kotlin code snippet that correctly creates a new map where each key is doubled and each value is squared from the original map mapOf(1 to 2, 3 to 4).
val original = mapOf(1 to 2, 3 to 4)
map returns a list of pairs, which can be converted back to a map with toMap().
Option D correctly maps each entry to a new pair with doubled key and squared value, then converts the list of pairs back to a map. Option D is invalid because mapValues lambda receives only the value, not key-value pair. Option D doubles keys but does not correctly pair them with squared values. Option D returns a list, not a map.
Given the code below, how many entries does the result map contain?
val input = mapOf("x" to 10, "y" to 20, "z" to 30) val result = input.mapKeys { it.key + it.value.toString() }.filterKeys { it.length > 2 }
Check the length of each new key after concatenation.
The new keys are "x10", "y20", and "z30". Each has length 3, which is greater than 2, so all three entries pass the filterKeys condition. Thus, the map contains 3 entries.