3

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.

2
  • 1
    Using Array<Int> involves autoboxing. For performance you should use IntArray. But I know this is a simple example. Commented May 9, 2018 at 12:55
  • I was just started studying Kotlin, thanks for the suggestion. Commented May 9, 2018 at 12:57

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

got answer as [Ljava.lang.Integer;@28a418fc while printing a.
sorry, review my edit please: println(a.contentToString())
3

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.

1 Comment

Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.