Kotlin can create an array by using the library function arrayOf():
fun main(args: Array<String>) { val array = arrayOf(1, 2, 3) //from w ww. j a v a2s .com println(array) }
Or, we can create an Array from an initial size and a function, which is used to generate each element:
fun main(args: Array<String>) { val perfectSquares = Array(10, { k -> k * k }) println(perfectSquares)/*from w w w . j a va 2 s. c o m*/ }
Kotlin arrays are regular collection classes.
Instances of arrays class have an iterator function and a size function, as well as a get and a set function.
The get and set functions are available through bracket syntax:
fun main(args: Array<String>) { val array = arrayOf(1, 2, 3) val element1 = array[0] val element2 = array[1] array[2] = 5 /*from www .j a v a 2s .co m*/ println(array) }
To avoid boxing types, Kotlin provides alternative array classes that are specialized for each of the primitive types.
The provided classes are ByteArray, CharArray, ShortArray, IntArray, LongArray, BooleanArray, FloatArray, and DoubleArray.