Issue
I'm new to Kotlin and found some behaviour that I did not expect.
This works:
println((1..10).map { it * 2 }) // [2, 4, ..., 20]
But this does not seem to iterate over anything and returns an empty list. I was expecting that I would get the reverse of the above list.
println((10..1).map { it * 2 }) // []
I didn't think a collection function should care about the order of the collection. Is there something I'm missing?
Solution
The ..
syntax is an alias for the rangeTo
function which gives an ascending range from the first to the last value inclusive.
So if the number following the ..
is less than number preceding, you get an empty range. This explains why you obtain an empty list when calling map
on it.
If you want a descending range, you need to use the downTo
function (documentation):
println((10 downTo 1).map { it * 2 })
// prints [20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
See playground.
Answered By - Simon Jacobs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.