Sobes.tech
Junior — Middle

How can you convert a collection of key-value pairs into a list of numbers using an extension function in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, to convert a collection of key-value pairs (Map) into a list of numbers, you can use extension functions such as map.

For example, if you have a Map<K, V>, and you want to get a list of values converted to numbers, you can do it like this:

val map = mapOf("a" to "1", "b" to "2", "c" to "3")

// Convert values to Int and collect into a list
val numbers: List<Int> = map.map { (_, value) -> value.toInt() }

println(numbers) // [1, 2, 3]

Here, map is an extension function that applies a lambda expression to each element of the collection and returns a new list.

If you need to convert pairs into numbers based on keys or combine key and value, you can modify the lambda:

val numbers = map.map { (key, value) -> key.length + value.toInt() }

Thus, Kotlin's extension functions allow for easy and concise transformation of collections.