I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll look at how we can initialize an array in Kotlin.

2. arrayOf Library Method

Kotlin has a built-in arrayOf method which converts the provided enumerated values into an array of the given type:

val strings = arrayOf("January", "February", "March")

3. Primitive Arrays

We can also use the arrayOf method with primitive values.

However, Kotlin will autobox the primitive values to their corresponding object wrapper classes which will have detrimental performance implications. To avoid this overhead Kotlin has wide support for primitive arrays. There are dedicated arrayOf methods for the following types: double, float, long, int, char, short, byte, boolean.

We can easily initialize a primitive int array using its dedicated arrayOf method:

val integers = intArrayOf(1, 2, 3, 4)

4. Late Initialization with Indices

Sometimes we don’t want to define the array’s values at instantiation. In this case, we can create an array of null values.

After instantiation, we can access and set the fields of the array. There are several ways to do this, but a common way is to use Kotlin’s indices property. This property returns a range of valid indices for the array. We can use range to access and set the values of the array in a for loop.

Let’s initialize our array with square numbers using this approach:

val array = arrayOfNulls<Number>(5)

for (i in array.indices) {
    array[i] = i * i
}

5. Generating Values with an Initializer

Primitive arrays and object arrays both have constructors that accept an initializer function as a second parameter. This initializer function takes the index as the input parameter, translates it into the appropriate value using the function, and inserts it into the array.

We can initialize an array with square numbers in one line:

val generatedArray = IntArray(10) { i -> i * i }

As mentioned, this kind of constructor is also available for object arrays:

val generatedStringArray = Array(10) { i -> "Number of index: $i"  }

6. Conclusion

In this tutorial, we saw how to initialize arrays in Kotlin. We discovered the wide range of support for primitive arrays. We also observed how we can use the array constructor with an initializer function to write concise code.

As always, the code is available over on GitHub.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of