Kotlin – Convert Range to List

Convert Range to List in Kotlin

To convert a given range to a list in Kotlin, call toList() function on the range object. The function returns an ArrayList object created with the elements of the range.

The syntax to convert a given range myRange to a list myList is

val myList = myRange.toList()

Examples

In the following examples, you will learn how to convert a given range object to a list.

Convert the range 4..9 into a list

In the following program, we take an integer range 4..9, and convert this range to a list.

Kotlin Program

fun main() {
    val myRange = 4..9
    val myList = myRange.toList()
    print(myList)
}

Output

[4, 5, 6, 7, 8, 9]

Convert the character range ‘a’..’z’ with a step of 3, into a list

In the following program, we take a character range 'a'..'z' with a step value of 3, and convert this range into a list

Kotlin Program

fun main() {
    val myRange = 'a'..'z' step 3
    val myList = myRange.toList()
    print(myList)
}

Output

[a, d, g, j, m, p, s, v, y]