1 Liners for List Comprehension-like operations?


#1

I was surprised to see that the otherwise very powerful sequence methods that Kotlin provides doesn’t seem to have a tool to do a one-liner list-comprehension-like operation. That is, I want to create a new list by defining its elements as an operation on the elements of some other list. I can do it in two lines using the forEach function, but is there a better 1 line way that I’m missing that is also cleaner?

Here is an example of the 2 liner I can do:

//input array we'll use
val initial = listOf<Int>(0, 1, 2, 3)

//2 line list comprehension equivalent that is original list, plus 1 on each element
val result = ArrayList<Int>(initial.size)
initial.forEach { it -> result.add(it+1) }

//verify
println(result)

#2

val result = initial.map { it + 1 } ?


#3

Oh wow, yes. For some reason I was confused in thinking that was their associate function, probably because of Java data structure names. Never mind then, nothing to see here :wink:


#4

Also, just FYI ranges are super useful here:

(0..3).map { it + 1 }
// or maybe just (1..4).toList()