Kotlin – Convert Range to Array

Convert Range to Array in Kotlin

To convert a given range to an array in Kotlin, convert the range to list and then this list into an array by calling toList() and toTypedArray() functions on the given range object as a chain.

The syntax to convert a given range myRange to an array myArray is

val myArray = myRange.toList().toTypedArray()

Examples

In the following examples, you will learn how to convert a given range object to an array. The type of the resulting array is based on the type of elements in the range.

Convert the range 4..9 into an array

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

Kotlin Program

fun main() {
    val myRange = 4..9
    val myArray = myRange.toList().toTypedArray()
    print(myArray.contentToString())
}

Output

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

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

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

Kotlin Program

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

Output

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