Using ranges for lists or arrays in Kotlin

Viewed 1316

I have tried and I failed. Which cases that "ranges" used for?

var list = listOf(1,2,3,4,5)

It's worked well. But following code didn't work as I wanted. Why?

var list = listOf(1 .. 5)

Runnable program is : https://pl.kotl.in/c5256MZEC.

3 Answers

That syntax creates a list of ranges (List<IntRange>) with a single range in it. You can convert a range (or any Iterable) to a List with toList():

(1..5).toList()

You can also iterate through it without having to convert it to a list

var list2 = 1..5
list2.forEach {
    println(it) 
}

Another option (same as @Tenfour04 response but more readable) is to use the rangeTo operator and convert it to a list with the same extension function toList:

val list = 1.rangeTo(5).toList()
Related