Kotlin array initialization example



An array is a collection of a fixed number of values. The array items are called elements of the array. Each element can be referred to by an index. Arrays are zero-based.
All Kotlin examples at All Kotlin Examples
Kotlin arrays are created with functions such as arrayOf() or intArrayOf(), or with classes such as IntArray or FloatArray.

Kotlin array initialization example

This example shows how we can initialize arrays in Kotlin:
import java.util.Arrays

fun main() {

    val nums = arrayOf(1, 2, 3, 4, 5)
    println(Arrays.toString(nums))

    val nums2 = (3..12).toList().toTypedArray()
    println(Arrays.toString(nums2))

    val nums3 = IntArray(5, { i -> i * 2 + 3})
    println(Arrays.toString(nums3))
}
Output:
[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[3, 5, 7, 9, 11]
All Kotlin examples at All Kotlin Examples

Comments