🧮 Kotlin – Arrays: Store and Access Indexed Data Easily
🧲 Introduction – Why Learn Kotlin Arrays?
Arrays in Kotlin are used to store a fixed-size collection of elements of the same type. Whether you’re handling numeric data, string lists, or object collections, arrays offer fast access, efficient storage, and concise syntax. Kotlin enhances traditional arrays with rich utility functions and type safety.
🎯 In this guide, you’ll learn:
- How to declare and initialize arrays
- Access and modify array elements
- Use array utility functions like
size
,first()
,last()
,contains()
- Best practices for array handling in Kotlin
📦 What Is an Array in Kotlin?
An array is a collection of values stored in a single variable, indexed from 0
.
🧱 Array Declaration & Initialization
✅ Using arrayOf()
function:
val fruits = arrayOf("Apple", "Banana", "Cherry")
✅ Using specific type arrays:
val numbers = intArrayOf(1, 2, 3, 4)
val doubles = doubleArrayOf(1.1, 2.2, 3.3)
- Kotlin has typed arrays for performance (e.g.,
IntArray
,DoubleArray
, etc.)
🔢 Accessing Array Elements
val names = arrayOf("John", "Jane", "Max")
println(names[0]) // John
println(names[2]) // Max
✅ Modifying elements:
names[1] = "Mary"
println(names[1]) // Mary
🧾 Array Properties and Methods
Property / Method | Description |
---|---|
size | Total number of elements |
first() | First element |
last() | Last element |
contains("x") | Checks if array contains value |
indexOf("x") | Returns index of element |
val cities = arrayOf("Delhi", "Mumbai", "Pune")
println(cities.size) // 3
println(cities.first()) // Delhi
println("Pune" in cities) // true
🔁 Looping Through Arrays
🔹 Using for
loop:
for (city in cities) {
println(city)
}
🔹 Using indices
:
for (i in cities.indices) {
println("City $i = ${cities[i]}")
}
🔁 Lambda with forEach()
cities.forEach { println("City: $it") }
📐 Creating Arrays Using Array()
Constructor
val squares = Array(5) { i -> i * i }
println(squares.joinToString()) // 0, 1, 4, 9, 16
- Creates an array of size 5 where each value is
i * i
.
🚫 Common Mistakes with Arrays
❌ Mistake | ✅ Fix |
---|---|
Using [] for declaration | Use arrayOf() or Array() in Kotlin |
Mixing types in an array | Stick to a single type or use Array<Any> |
Accessing out-of-bound index | Always check .size before indexing |
Mutating immutable arrays | Use val for reference immutability; var to reassign |
✅ Best Practices for Arrays in Kotlin
Practice | Reason |
---|---|
Use typed arrays for performance | IntArray , DoubleArray , etc., are more efficient |
Prefer val for fixed data | Prevents accidental reassignment |
Use utility functions | Improves readability and safety |
Use .joinToString() for printing | Gives cleaner string representation |
📌 Summary – Recap & Next Steps
Kotlin arrays are versatile containers for storing same-type elements with index-based access. With powerful helper functions and clean syntax, they’re easy to use and integrate with Kotlin’s functional features.
🔍 Key Takeaways:
- Use
arrayOf()
ortypedArrayOf()
to create arrays - Access elements via index, iterate with
for
,indices
, orforEach
- Built-in functions like
size
,first()
, andcontains()
boost productivity - Avoid index errors by checking bounds
⚙️ Practical Use:
Useful for sensor data, UI item storage, form field validation, or basic algorithm tasks in Kotlin Android and backend development.
❓ FAQs – Kotlin Arrays
❓ How do I declare an array in Kotlin?
✅ Use arrayOf()
:
val nums = arrayOf(1, 2, 3)
❓ What’s the difference between arrayOf()
and intArrayOf()
?
✅ intArrayOf()
returns a primitive IntArray
, which is more efficient in memory than Array<Int>
.
❓ How do I get the length of an array?
✅ Use .size
:
val arr = arrayOf(1, 2, 3)
println(arr.size)
❓ How can I create an array with computed values?
✅ Use the Array()
constructor:
val squares = Array(5) { i -> i * i }
❓ Can I change the size of an array in Kotlin?
✅ No. Arrays have fixed size. Use MutableList
for dynamic collections.
Share Now :