Array Initialization in Kotlin
Introduction
Array Initialization is a fundamental concept every Kotlin developer should understand. Arrays store a fixed number of elements in memory with fast index-based access. They are useful when size is known upfront or when interoping with Java APIs.
The Array(size) { index -> value } syntax creates and initializes an array. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The Array(size) { index -> value } syntax creates and initializes an array.
- Each index can produce a different value using a lambda.
- This is useful for computed initial values.
Syntax
Array(5) { it * 2 }Array Initialization in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val squares = Array(5) { index -> index * index }
for (value in squares) {
print("$value ")
}
}Sample Output
0 1 4 9 16When to use
Use arrays when you need fixed-size storage, primitive arrays without boxing overhead, or compatibility with Java vararg APIs.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val squares = Array(5) { index -> index * index }assigns or updates a value used later in the program. -
The Array(size) { index -> value } syntax creates and initializes an array.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- The Array(size) { index -> value } syntax creates and initializes an array.
- Each index can produce a different value using a lambda.
- This is useful for computed initial values.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.