Arrays in Kotlin are fixed-size collections that store elements of the same type. They provide a convenient way to work with ordered sets of data, offering efficient access and manipulation of elements.
Kotlin offers several ways to create arrays:
val numbers = arrayOf(1, 2, 3, 4, 5)
val fruits = arrayOf("apple", "banana", "orange")
val squares = Array(5) { i -> i * i }
// Creates an array: [0, 1, 4, 9, 16]
Kotlin provides specialized classes for primitive types to avoid boxing overhead:
val intArray = intArrayOf(1, 2, 3, 4, 5)
val doubleArray = doubleArrayOf(1.0, 2.0, 3.0)
Array elements can be accessed and modified using index notation:
val fruits = arrayOf("apple", "banana", "orange")
println(fruits[1]) // Output: banana
fruits[1] = "grape"
println(fruits[1]) // Output: grape
Kotlin arrays come with useful properties and functions:
size
: Returns the number of elements in the arrayindices
: Returns the valid indices range for the arrayisEmpty()
: Checks if the array is emptycontains(element)
: Checks if the array contains a specific elementKotlin provides several ways to iterate over arrays:
val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}
val fruits = arrayOf("apple", "banana", "orange")
for (i in fruits.indices) {
println("$i: ${fruits[i]}")
}
val colors = arrayOf("red", "green", "blue")
for ((index, value) in colors.withIndex()) {
println("$index: $value")
}
Kotlin arrays support various operations:
val numbers = arrayOf(3, 1, 4, 1, 5, 9)
numbers.sort()
println(numbers.contentToString()) // Output: [1, 1, 3, 4, 5, 9]
val numbers = arrayOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4]
val numbers = arrayOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
println(squared) // Output: [1, 4, 9, 16, 25]
Kotlin supports multi-dimensional arrays, which are essentially arrays of arrays:
val matrix = Array(3) { Array(3) { 0 } }
matrix[0][0] = 1
matrix[1][1] = 5
matrix[2][2] = 9
for (row in matrix) {
println(row.contentToString())
}
IntArray
, DoubleArray
) for better performance when working with primitive types.ArrayIndexOutOfBoundsException
.Arrays in Kotlin provide a powerful tool for managing ordered collections of data. By understanding their creation, manipulation, and common operations, you can effectively utilize arrays in your Kotlin programs.