Sachin Varma
Sachin Varma

Reputation: 2235

Array declaration in Kotlin

The code below is an example for Array declaration in Kotlin,

fun main(args: Array<String>) {

    var a = Array<Int>(2){0}
    a[0] = 100
    a[1] = 200
    print(a[1])

}

Here variable a is an array of size 2 and having values 100 and 200 and it is printing the value of a[1] as 200.

My question is -> What is the role of "0" in var a = Array(2){0}?

I changed the value of "0" to some other integer value, still it is working fine, but i was not able to find the use case of it. Can anyone explain it?

Any help will be appreciated.

Thanks.

Upvotes: 3

Views: 4072

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81869

The 0 is what you initialize each element of your array (2 in your case) with, using the following constructor:

public inline constructor(size: Int, init: (Int) -> T)

You can make this visible by printing the array directly after its initialization:

var a = Array<Int>(2){0}
println(a.contentToString())

Please consider the use of arrayOf(0,0) for such a simple use case, which is more idiomatic.

Upvotes: 6

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Arrays in Kotlin are represented by the Array class, that has get and set functions (that turn into [] by operator overloading conventions), and size property, along with a few other useful member functions:

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit

    operator fun iterator(): Iterator<T>
    // ...
}

You can write

var a = Array(2){0}

Creates a new array with the specified [size], where each element is calculated by calling the specified * [init] function. The [init] function returns an array element given its index.

 public inline constructor(size: Int, init: (Int) -> T)

Read Arrays in Kotlin.

Upvotes: 3

Related Questions