Tutorial by Examples

Generic arrays in Kotlin are represented by Array<T>. To create an empty array, use emptyArray<T>() factory function: val empty = emptyArray<String>() To create an array with given size and initial values, use the constructor: var strings = Array<String>(size = 5, init ...
These types do not inherit from Array<T> to avoid boxing, however, they have the same attributes and methods. Kotlin typeFactory functionJVM typeBooleanArraybooleanArrayOf(true, false)boolean[]ByteArraybyteArrayOf(1, 2, 3)byte[]CharArraycharArrayOf('a', 'b', 'c')char[]DoubleArraydoubleArrayOf...
average() is defined for Byte, Int, Long, Short, Double, Float and always returns Double: val doubles = doubleArrayOf(1.5, 3.0) print(doubles.average()) // prints 2.25 val ints = intArrayOf(1, 4) println(ints.average()) // prints 2.5 component1(), component2(), ... component5() return an it...
You can print the array elements using the loop same as the Java enhanced loop, but you need to change keyword from : to in. val asc = Array(5, { i -> (i * i).toString() }) for(s : String in asc){ println(s); } You can also change data type in for loop. val asc = Array(5, { i -> (i...
val a = arrayOf(1, 2, 3) // creates an Array<Int> of size 3 containing [1, 2, 3].
val a = Array(3) { i -> i * 2 } // creates an Array<Int> of size 3 containing [0, 2, 4]
val a = arrayOfNulls<Int>(3) // creates an Array<Int?> of [null, null, null] The returned array will always have a nullable type. Arrays of non-nullable items can't be created uninitialized.

Page 1 of 1