Sobes.tech
Junior — Middle

Is it possible to apply extension functions in Kotlin to calculate the sum of elements based on a certain condition in collections with keys and values?

sobes.tech AI

Answer from AI

Yes, in Kotlin, you can use extension functions to calculate the sum of elements in collections with keys and values, applying conditions. For example, for Map<K, V>, you can use the filter function to select the desired pairs, and then sumOf to compute the sum based on the value or some computed parameter.

Example:

val map = mapOf("a" to 10, "b" to 20, "c" to 30)
val sum = map.filter { it.key != "b" }.sumOf { it.value }
println(sum) // Outputs 40 (10 + 30)

Thus, extension functions allow for convenient and concise operations.