Recall & Review
beginner
What does the
associate function do in Kotlin?The
associate function creates a Map by transforming elements of a collection into key-value pairs.Click to reveal answer
beginner
How do you create a map from a list of strings where keys are the strings and values are their lengths using
associate?You can use: <br>
val map = list.associate { it to it.length }<br>This creates a map where each string is a key and its length is the value.Click to reveal answer
intermediate
What is the difference between
associate and associateBy in Kotlin?associate creates a map from key-value pairs you define.<br>associateBy creates a map where keys are generated from elements, and values are the elements themselves.Click to reveal answer
intermediate
Can
associate handle duplicate keys? What happens if duplicates exist?If duplicate keys are created, the last value for that key will overwrite previous ones in the resulting map.
Click to reveal answer
beginner
Write a Kotlin code snippet using
associate to map a list of numbers to their squares.Example:<br>
val numbers = listOf(1, 2, 3)<br>val map = numbers.associate { it to it * it }<br>This creates a map like {1=1, 2=4, 3=9}.Click to reveal answer
What does the Kotlin
associate function return?✗ Incorrect
associate transforms a collection into a Map by creating key-value pairs.Which of the following is a valid use of
associate?✗ Incorrect
associate requires a lambda returning a Pair (key to value).If duplicate keys are generated by
associate, what happens?✗ Incorrect
The last value for a duplicate key overwrites earlier ones in the map.
What is the difference between
associate and associateBy?✗ Incorrect
associate needs pairs; associateBy uses a key selector and maps keys to elements.Which Kotlin collection function would you use to create a map from a list where keys are elements and values are their lengths?
✗ Incorrect
associate is used to create maps from collections by defining key-value pairs.Explain how the
associate function works in Kotlin and give an example.Think about turning a list into a map by pairing each item with a value.
You got /3 concepts.
What happens if duplicate keys are created when using
associate? How can you handle this?Focus on map behavior with duplicate keys.
You got /3 concepts.