How to declare and initialize an array in Kotlin with example
This tutorial explains about multiple ways to declare and initialize an array of different values with examples.
Arrays in Kotlin are declared with a type of Array
class, It contains size property and set and get functions
How to declare array in Kotlin
Arrays can be declared with multiple ways.
- one way using Array constructor
Arrays can be declared with predefined size as given below
Syntax
Array(size){default initialized values}
Here is an example
var array = Array<Int>(4){0} //[0, 0, 0, 0]
The above syntax creates an array of Int type with a size of 4 elements, and each element is initilized with default value.
- Another way using arrayOf function arrayOf functions is a generic function, accepts values,
var numbers = arrayOf("one","two","three","four","five")
println(numbers.contentToString())
compiler infer the Type of the Array based on the values of an Array, Here is it is a String or super class of this.
The same can be declared type after variable declaration
var numbers: Array<String> = arrayOf("one","two","three","four","five")
You can replace arrayOf
var numbers = arrayOf<String>("one","two","three","four","five")