Kotlin Arrays
Arrays are one of the most fundamental data structures in programming. In Kotlin, arrays provide a way to store a fixed number of elements of the same type in a contiguous block of memory. Unlike some other collections in Kotlin, arrays are mutable but have a fixed size that is determined when they are created.
Introduction to Kotlin Arrays
An array in Kotlin is represented by the Array
class, which contains functions like get
, set
, and properties like size
. Kotlin arrays are different from Java arrays in that they are invariant, meaning an Array<String>
cannot be assigned to an Array<Any>
.
Arrays in Kotlin come in two flavors:
- Reference type arrays - Store object references (
Array<T>
) - Primitive type arrays - Special classes for primitive types to avoid boxing overhead (e.g.,
IntArray
,DoubleArray
)
Creating Arrays in Kotlin
Using the arrayOf()
Function
The simplest way to create an array is using the arrayOf()
function:
val fruits = arrayOf("Apple", "Banana", "Orange", "Mango")
println("Fruits array: ${fruits.contentToString()}")
Output:
Fruits array: [Apple, Banana, Orange, Mango]
Creating Arrays of Primitive Types
For primitive types, Kotlin provides specialized classes to avoid the overhead of boxing:
val numbers = intArrayOf(1, 2, 3, 4, 5)
val doubles = doubleArrayOf(1.0, 2.0, 3.0, 4.0)
val booleans = booleanArrayOf(true, false, true)
println("Integer array: ${numbers.contentToString()}")
println("Double array: ${doubles.contentToString()}")
println("Boolean array: ${booleans.contentToString()}")
Output:
Integer array: [1, 2, 3, 4, 5]
Double array: [1.0, 2.0, 3.0, 4.0]
Boolean array: [true, false, true]
Creating Arrays with a Constructor
You can create arrays using the Array constructor with a size and an initializer:
// Creating an Array of size 5 with default value 0
val zeros = Array(5) { 0 }
println("Array of zeros: ${zeros.contentToString()}")
// Creating an Array with calculated values
val squares = Array(5) { i -> i * i }
println("Array of squares: ${squares.contentToString()}")
Output:
Array of zeros: [0, 0, 0, 0, 0]
Array of squares: [0, 1, 4, 9, 16]
Empty Arrays
You can create empty arrays when you don't yet have data but need to initialize the variable:
val emptyStringArray = emptyArray<String>()
println("Empty array length: ${emptyStringArray.size}")
Output:
Empty array length: 0
Accessing and Modifying Array Elements
Using Indexing Operator
Kotlin arrays are zero-indexed, meaning the first element has index 0:
val colors = arrayOf("Red", "Green", "Blue", "Yellow")
// Accessing elements
println("First color: ${colors[0]}")
println("Second color: ${colors[1]}")
// Modifying elements
colors[0] = "Crimson"
println("Modified first color: ${colors[0]}")
println("Updated array: ${colors.contentToString()}")
Output:
First color: Red
Second color: Green
Modified first color: Crimson
Updated array: [Crimson, Green, Blue, Yellow]
Using get() and set() Functions
The indexing operators actually call the get()
and set()
functions:
val planets = arrayOf("Mercury", "Venus", "Earth", "Mars")
// Using get() function
println("Third planet: ${planets.get(2)}")
// Using set() function
planets.set(3, "Jupiter")
println("Modified array: ${planets.contentToString()}")
Output:
Third planet: Earth
Modified array: [Mercury, Venus, Earth, Jupiter]
Array Properties and Operations
Checking Array Size
The size
property returns the number of elements in the array:
val weekDays = arrayOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
println("Number of weekdays: ${weekDays.size}")
Output:
Number of weekdays: 5
Iterating Over Arrays
There are several ways to iterate through arrays in Kotlin:
val animals = arrayOf("Lion", "Tiger", "Elephant", "Giraffe")
// Using for loop with direct access
println("Animals (simple for loop):")
for (animal in animals) {
println(animal)
}
// Using for loop with indices
println("\nAnimals with indices:")
for (index in animals.indices) {
println("Animal at position $index is ${animals[index]}")
}
// Using forEach with lambda
println("\nAnimals (forEach):")
animals.forEach { animal ->
println(animal)
}
// Using forEachIndexed with lambda
println("\nAnimals (forEachIndexed):")
animals.forEachIndexed { index, animal ->
println("Animal #${index + 1}: $animal")
}
Output:
Animals (simple for loop):
Lion
Tiger
Elephant
Giraffe
Animals with indices:
Animal at position 0 is Lion
Animal at position 1 is Tiger
Animal at position 2 is Elephant
Animal at position 3 is Giraffe
Animals (forEach):
Lion
Tiger
Elephant
Giraffe
Animals (forEachIndexed):
Animal #1: Lion
Animal #2: Tiger
Animal #3: Elephant
Animal #4: Giraffe
Searching Elements in Arrays
Kotlin provides functions for finding elements in arrays:
val scores = intArrayOf(85, 92, 78, 96, 88)
println("Contains 92: ${92 in scores}") // Using 'in' operator
println("Index of 78: ${scores.indexOf(78)}")
println("Contains 100: ${scores.contains(100)}")
println("First score above 90: ${scores.first { it > 90 }}")
println("Any score below 80: ${scores.any { it < 80 }}")
println("All scores above 75: ${scores.all { it > 75 }}")
Output:
Contains 92: true
Index of 78: 2
Contains 100: false
First score above 90: 92
Any score below 80: true
All scores above 75: true
Array Transformations
Filtering Arrays
You can filter arrays to create new arrays with elements that match certain conditions:
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenNumbers = numbers.filter { it % 2 == 0 }
val oddNumbers = numbers.filter { it % 2 != 0 }
println("Even numbers: $evenNumbers")
println("Odd numbers: $oddNumbers")
Output:
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]
Mapping Arrays
You can transform each element in an array using the map
function:
val numbers = arrayOf(1, 2, 3, 4, 5)
// Doubling each number
val doubled = numbers.map { it * 2 }
println("Original numbers: ${numbers.contentToString()}")
println("Doubled numbers: $doubled")
// Converting to strings
val numberStrings = numbers.map { "Number $it" }
println("As strings: $numberStrings")
Output:
Original numbers: [1, 2, 3, 4, 5]
Doubled numbers: [2, 4, 6, 8, 10]
As strings: [Number 1, Number 2, Number 3, Number 4, Number 5]
Sorting Arrays
Arrays can be sorted using various methods:
val unsortedNumbers = arrayOf(5, 2, 9, 1, 7, 3)
val unsortedNames = arrayOf("Zoe", "Alex", "Charlie", "Bob")
// Sorting in place
unsortedNumbers.sort()
unsortedNames.sort()
println("Sorted numbers: ${unsortedNumbers.contentToString()}")
println("Sorted names: ${unsortedNames.contentToString()}")
// Creating a sorted copy
val randomNumbers = arrayOf(23, 5, 16, 8, 42)
val sortedNumbers = randomNumbers.sortedArray()
val descendingNumbers = randomNumbers.sortedArrayDescending()
println("Original array: ${randomNumbers.contentToString()}")
println("Sorted array: ${sortedNumbers.contentToString()}")
println("Descending sorted array: ${descendingNumbers.contentToString()}")
Output:
Sorted numbers: [1, 2, 3, 5, 7, 9]
Sorted names: [Alex, Bob, Charlie, Zoe]
Original array: [23, 5, 16, 8, 42]
Sorted array: [5, 8, 16, 23, 42]
Descending sorted array: [42, 23, 16, 8, 5]
Multi-Dimensional Arrays
Kotlin supports multi-dimensional arrays, which are essentially arrays of arrays:
// Creating a 3x3 matrix using Array constructor
val matrix = Array(3) { row ->
Array(3) { col ->
row * 3 + col + 1
}
}
println("Matrix:")
for (row in matrix) {
println(row.contentToString())
}
// Accessing elements in a 2D array
println("\nElement at position [1,2]: ${matrix[1][2]}")
Output:
Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Element at position [1,2]: 6
Practical Examples
Example 1: Temperature Analysis
Let's use arrays to analyze a week's worth of temperature data:
fun analyzeTemperatures(temperatures: DoubleArray) {
val average = temperatures.average()
val max = temperatures.maxOrNull() ?: 0.0
val min = temperatures.minOrNull() ?: 0.0
println("Temperature analysis:")
println("Average temperature: %.1f°C".format(average))
println("Maximum temperature: %.1f°C".format(max))
println("Minimum temperature: %.1f°C".format(min))
println("Days above average: ${temperatures.count { it > average }}")
}
// Daily temperatures for a week in Celsius
val weeklyTemperatures = doubleArrayOf(23.5, 25.0, 21.8, 24.2, 27.5, 26.1, 22.8)
println("Temperatures: ${weeklyTemperatures.contentToString()}")
analyzeTemperatures(weeklyTemperatures)
Output:
Temperatures: [23.5, 25.0, 21.8, 24.2, 27.5, 26.1, 22.8]
Temperature analysis:
Average temperature: 24.4°C
Maximum temperature: 27.5°C
Minimum temperature: 21.8°C
Days above average: 3
Example 2: Simple Grade Calculator
Let's create a simple grade calculator that uses arrays to store and process student grades:
fun calculateGrades(scores: IntArray): String {
val average = scores.average()
return when {
average >= 90 -> "A"
average >= 80 -> "B"
average >= 70 -> "C"
average >= 60 -> "D"
else -> "F"
}
}
fun printStudentReport(name: String, scores: IntArray) {
val total = scores.sum()
val average = scores.average()
val grade = calculateGrades(scores)
println("\nStudent Report: $name")
println("Scores: ${scores.contentToString()}")
println("Total Points: $total")
println("Average Score: %.1f".format(average))
println("Final Grade: $grade")
}
// Student data
val student1Scores = intArrayOf(85, 92, 78, 90, 88)
val student2Scores = intArrayOf(72, 65, 70, 68, 74)
printStudentReport("Alice Smith", student1Scores)
printStudentReport("Bob Johnson", student2Scores)
Output:
Student Report: Alice Smith
Scores: [85, 92, 78, 90, 88]
Total Points: 433
Average Score: 86.6
Final Grade: B
Student Report: Bob Johnson
Scores: [72, 65, 70, 68, 74]
Total Points: 349
Average Score: 69.8
Final Grade: C
Example 3: Word Frequency Counter
Here's an example of using arrays to analyze word frequencies in a text:
fun countWordFrequency(text: String): Map<String, Int> {
val words = text.lowercase()
.replace(Regex("[^a-z ]"), "")
.split(" ")
.filter { it.isNotEmpty() }
.toTypedArray()
val frequencyMap = mutableMapOf<String, Int>()
for (word in words) {
frequencyMap[word] = (frequencyMap[word] ?: 0) + 1
}
return frequencyMap.toList().sortedByDescending { it.second }.toMap()
}
val sampleText = """
Kotlin is a modern programming language that makes developers happier.
Kotlin is concise, safe, interoperable, and tool-friendly.
Many developers love Kotlin for its clarity and efficiency.
""".trimIndent()
println("Original text:")
println(sampleText)
println("\nWord frequency analysis:")
val wordFrequency = countWordFrequency(sampleText)
wordFrequency.entries.forEach { (word, count) ->
println("\"$word\" appears $count time${if (count > 1) "s" else ""}")
}
Output:
Original text:
Kotlin is a modern programming language that makes developers happier.
Kotlin is concise, safe, interoperable, and tool-friendly.
Many developers love Kotlin for its clarity and efficiency.
Word frequency analysis:
"kotlin" appears 3 times
"is" appears 2 times
"developers" appears 2 times
"a" appears 1 time
"modern" appears 1 time
"programming" appears 1 time
...
Arrays vs Other Collections
It's important to understand when to use arrays versus other collection types in Kotlin:
Feature | Arrays | Lists | Sets | Maps |
---|---|---|---|---|
Size | Fixed | Flexible | Flexible | Flexible |
Mutability | Always mutable | Can be mutable or immutable | Can be mutable or immutable | Can be mutable or immutable |
Element Access | O(1) | O(1) for ArrayList, O(n) for LinkedList | O(1) average | O(1) average |
Ordering | Maintains order | Maintains order | No guaranteed order (except LinkedHashSet) | No guaranteed order (except LinkedHashMap) |
Duplicates | Allowed | Allowed | Not allowed | Keys must be unique |
Arrays are best used when:
- You need a fixed-size collection
- You need the most efficient memory representation (especially for primitive types)
- You're interfacing with Java APIs that expect arrays
- Performance is critical and you need direct indexed access
Summary
In this guide, we've covered:
- Creating arrays in Kotlin using various methods
- Accessing and modifying array elements
- Common array properties and operations
- Transforming arrays with filtering, mapping, and sorting
- Working with multi-dimensional arrays
- Practical examples of using arrays in real applications
Arrays are a fundamental data structure in Kotlin and provide efficient storage for fixed-size collections of elements. While Kotlin provides many higher-level collection types, arrays remain important for performance-critical code and interoperability with Java.
Exercises
- Create an array of your 5 favorite books and write a function that prints each book with its index number.
- Write a function that takes an array of integers and returns a new array with only the unique values.
- Create a 2D array representing a tic-tac-toe board and write functions to check for wins.
- Implement a function that takes an array of strings and returns the longest string.
- Write a program that uses arrays to calculate the standard deviation of a set of numbers.
- Create a function that takes two arrays and returns a new array containing elements that appear in both input arrays.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)