Question

How to Initialize Arrays in Kotlin with Values

kotlinarrays

Question

In Java, you can initialize an array like this:

int numbers[] = new int[] {10, 20, 30, 40, 50};

How do you initialize an array with values in Kotlin?

Short Answer

By the end of this page, you will understand how to create arrays in Kotlin using predefined values, when to use arrayOf(...), when to use primitive array types like intArrayOf(...), and how Kotlin array syntax differs from Java.

Concept

Kotlin supports arrays, but its syntax is different from Java.

In Java, array creation often uses a type followed by square brackets and a new expression. Kotlin does not use new, and array creation is usually done through functions such as arrayOf(...).

For example:

val numbers = arrayOf(10, 20, 30, 40, 50)

This creates an Array<Int>.

However, Kotlin also has primitive array types for better performance:

  • IntArray
  • DoubleArray
  • BooleanArray
  • CharArray
  • LongArray
  • FloatArray
  • ShortArray
  • ByteArray

So if you specifically want an array of primitive Int values, Kotlin commonly uses:

val numbers = intArrayOf(10, 20, 30, 40, 50)

This matters because Kotlin distinguishes between:

  • Array<Int> → array of boxed Int objects
  • IntArray → array of primitive int values

In real programs, choosing the right one can affect performance, interoperability with Java, and API expectations.

A key idea is that Kotlin prefers factory functions instead of special syntax for many object creations. Arrays are a good example of that style.

Mental Model

Think of a Kotlin array as a row of numbered boxes.

  • Each box has a position: 0, 1, 2, and so on.
  • You can fill the boxes with values when you create the array.
  • arrayOf(...) is like saying: "Create a row of boxes and put these items in them."
  • intArrayOf(...) is like saying: "Create a row of integer boxes specifically for Int values."

So instead of Java's new int[] {...}, Kotlin says: "Use this array-building function and provide the values."

Take Quiz

Syntax and Examples

Basic array initialization

val numbers = arrayOf(10, 20, 30, 40, 50)

This creates an Array<Int>.

Primitive integer array

val numbers = intArrayOf(10, 20, 30, 40, 50)

This creates an IntArray.

String array

val names = arrayOf("Alice", "Bob", "Charlie")

This creates an Array<String>.

Accessing values

val numbers = intArrayOf(10, 20, 30)
println(numbers[0]) // 10
println(numbers[1]) // 20

Creating an array by size and initializer

val squares = Array(5) { index -> index * index }
println(squares.joinToString()) // 0, 1, 4, 9, 16

This creates an array with 5 elements. Each value is generated from its index.

Which one should beginners use?

  • Use arrayOf(...) for general-purpose object arrays.
  • Use intArrayOf(...) and other primitive array types when you specifically want primitive arrays.
  • If you are working with collections often, remember that Kotlin developers also commonly use listOf(...), which is different from arrays.

Step by Step Execution

Consider this example:

val numbers = intArrayOf(10, 20, 30)
println(numbers[0])
println(numbers[2])

Step by step:

  1. intArrayOf(10, 20, 30) creates an array containing three integers.
  2. The array is stored in the variable numbers.
  3. numbers[0] reads the first element, which is 10.
  4. println(numbers[0]) prints 10.
  5. numbers[2] reads the third element, which is 30.
  6. println(numbers[2]) prints 30.

Output:

10
30

Here is another traceable example:

val values = Array(4) { index -> index + 1 }
println(values.joinToString())

What happens:

  1. Array(4) means the array will have 4 elements.
  2. The initializer runs once for each index.
  3. When index is 0, value becomes 1.
  4. When index is 1, value becomes 2.
  5. When index is 2, value becomes 3.
  6. When index is 3, value becomes 4.
  7. The final array is [1, 2, 3, 4].
  8. joinToString() converts it to a readable string for printing.

Real World Use Cases

Arrays in Kotlin are useful when you need fixed-size indexed data.

Common examples

  • Storing numeric data such as scores, coordinates, or sensor readings
  • Working with Java APIs that expect arrays
  • Processing command-line arguments or fixed sets of values
  • Image or audio data where indexed access matters
  • Performance-sensitive code using primitive arrays like IntArray

Example: fixed monthly sales values

val sales = intArrayOf(120, 150, 90, 200)
println(sales[3]) // 200

Example: passing arrays to functions

fun printNames(names: Array<String>) {
    for (name in names) {
        println(name)
    }
}

val team = arrayOf("Ana", "Ben", "Chris")
printNames(team)

Example: generated values

val evenNumbers = IntArray(5) { it * 2 }
println(evenNumbers.joinToString()) // 0, 2, 4, 6, 8
Take Quiz

Real Codebase Usage

In real Kotlin codebases, arrays are used less often than lists, but they are still important.

Common patterns

Interoperating with Java

Many Java libraries use arrays in method parameters or return types.

val args = arrayOf("--debug", "--port=8080")

Using primitive arrays for performance

If a program handles many numeric values, developers often prefer primitive arrays.

val temperatures = DoubleArray(7)

Initializing from known constants

Configuration-like values may be stored in arrays when the size is fixed.

val supportedCodes = arrayOf("en", "es", "fr")

Transforming data for APIs

Developers may build arrays from collections before calling functions that require arrays.

val namesList = listOf("Alice", "Bob")
val namesArray = namesList.toTypedArray()

Guarding against invalid access

Because arrays are index-based, developers often validate indices before use.

fun safeRead(values: IntArray, index: Int): Int? {
    return if (index in values.indices) values[index] else null
}

Common Mistakes

1. Expecting Java syntax to work in Kotlin

Broken code:

val numbers = new int[] {10, 20, 30}

Why it fails:

  • Kotlin does not use new.
  • Kotlin does not use Java's array literal syntax.

Correct version:

val numbers = intArrayOf(10, 20, 30)

2. Confusing Array<Int> with IntArray

val a = arrayOf(1, 2, 3)   // Array<Int>
val b = intArrayOf(1, 2, 3) // IntArray

These are not the same type.

Avoid this mistake by checking what a function expects.

3. Using the wrong constructor style

Broken idea:

val numbers = Array<Int>(5)

Why it fails:

  • Array needs both a size and an initializer function.

Correct version:

val numbers = Array(5) { 0 }

4. Accessing an index that does not exist

Broken code:

val numbers = intArrayOf(10, 20, 30)
println(numbers[3])

Why it fails:

  • Valid indices are 0, 1, and 2.

Safer approach:

if (3 in numbers.indices) {
    println(numbers[3])
}

5. Assuming arrays grow automatically

Arrays have fixed size after creation.

If you need a resizable structure, use a list such as mutableListOf(...) instead.

Comparisons

Arrays in Kotlin compared

ConceptSyntaxSizeTypical use
Array<T>arrayOf(1, 2, 3)FixedGeneral object values
IntArrayintArrayOf(1, 2, 3)FixedPrimitive integers, better performance
List<T>listOf(1, 2, 3)Read-only interfaceMost everyday Kotlin code
MutableList<T>mutableListOf(1, 2, 3)ResizableWhen elements need to be added or removed

Array<Int> vs IntArray

FeatureArray<Int>IntArray
Storesboxed Int objectsprimitive int values
Created witharrayOf(...)intArrayOf(...)
Performanceusually less efficient for heavy numeric workusually better for numeric work
Genericyesno

Kotlin arrays vs Java arrays

JavaKotlin
new int[] {1, 2, 3}intArrayOf(1, 2, 3)
new String[] {"a", "b"}arrayOf("a", "b")
new int[5]IntArray(5)
new String[5]arrayOfNulls<String>(5) or Array(5) { ... }
Take Quiz

Cheat Sheet

Quick syntax

val a = arrayOf(1, 2, 3)          // Array<Int>
val b = intArrayOf(1, 2, 3)       // IntArray
val c = arrayOf("a", "b")       // Array<String>
val d = Array(3) { it * 10 }      // Array<Int>: [0, 10, 20]
val e = IntArray(3) { it + 1 }    // IntArray: [1, 2, 3]

Rules to remember

  • Kotlin does not use new for arrays.
  • arrayOf(...) creates a generic object array.
  • intArrayOf(...) creates a primitive integer array.
  • Arrays have fixed size.
  • Indexing starts at 0.
  • Use array[index] to read or update values.

Useful helpers

println(arr.size)
println(arr.indices)
println(arr.joinToString())

Common primitive array creators

  • intArrayOf(...)
  • doubleArrayOf(...)
  • booleanArrayOf(...)
  • charArrayOf(...)
  • longArrayOf(...)

When to use lists instead

Use listOf(...) or mutableListOf(...) when you want collection-style operations or a resizable structure.

FAQ

How do you initialize an array in Kotlin with values?

Use arrayOf(...) for general arrays or intArrayOf(...) for primitive integers.

val numbers = intArrayOf(10, 20, 30)

What is the Kotlin equivalent of new int[] { ... } in Java?

The closest Kotlin equivalent is:

val numbers = intArrayOf(10, 20, 30)

Should I use arrayOf or intArrayOf in Kotlin?

Use arrayOf(...) for generic object arrays. Use intArrayOf(...) when you need an IntArray with primitive integers.

Are Kotlin arrays fixed size?

Yes. Once created, an array's size cannot change.

What is the difference between Array<Int> and List<Int> in Kotlin?

Array<Int> is a fixed-size indexed structure. List<Int> is a collection interface and is more commonly used in everyday Kotlin code.

How do I create an empty array in Kotlin?

For a generic empty array:

val empty = emptyArray<String>()

For primitive integers:

val emptyInts = intArrayOf()

Can I create an array with generated values in Kotlin?

Yes.

val values = Array(5) { it * 2 }
Take Quiz

Mini Project

Description

Build a small Kotlin program that stores a week's daily temperatures in an array and prints useful information. This project demonstrates how to initialize arrays with values, access elements by index, and iterate through array contents.

Goal

Create a Kotlin program that initializes an array with temperature values and prints the first, last, and all temperatures.

Requirements

  1. Create an integer array containing 7 temperature values.
  2. Print the first temperature using index access.
  3. Print the last temperature using its index.
  4. Loop through the array and print every temperature.
  5. Print the full array in a readable format.
Take Quiz

Keep learning

Related questions

View more