Arrays in Kotlin are used to store multiple values of the same type in a single variable. Kotlin arrays are easy to work with and come with built-in functions.
You can declare an array using arrayOf() or using Array() constructor.
// Using arrayOf()
val numbers = arrayOf(1, 2, 3, 4, 5)
// Using Array() constructor
val squares = Array(5) { i -> (i * i) }
println(numbers.joinToString(", ")) // Output: 1, 2, 3, 4, 5
println(squares.joinToString(", ")) // Output: 0, 1, 4, 9, 16
Array elements can be accessed using an index, starting from 0.
val colors = arrayOf("Red", "Green", "Blue")
println(colors[0]) // Output: Red
println(colors[1]) // Output: Green
println(colors[2]) // Output: Blue
You can modify array elements by using their index.
val fruits = arrayOf("Apple", "Banana", "Cherry")
fruits[1] = "Blueberry"
println(fruits.joinToString(", ")) // Output: Apple, Blueberry, Cherry
You can get the size of an array using the size property.
val numbers = arrayOf(10, 20, 30, 40)
println("Array size: ${numbers.size}") // Output: Array size: 4
You can loop through an array using a for loop:
val names = arrayOf("Alice", "Bob", "Charlie")
for (name in names) {
println(name)
}
joinToString() to quickly format arrays into a readable string.
Kotlin arrays come with several built-in functions to make them even more powerful:
val numbers = arrayOf(1, 2, 3, 4, 5)
println(numbers.sum()) // Output: 15
println(numbers.average()) // Output: 3.0
println(numbers.maxOrNull()) // Output: 5
println(numbers.sortedArray().joinToString(", ")) // Output: 1, 2, 3, 4, 5
maxOrNull() to safely get the maximum value in an array.
You can also create an array that contains null values:
val nullArray = arrayOfNulls(5) println(nullArray.joinToString(", ")) // Output: null, null, null, null, null
Practice these challenges:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!