Kotlin Arrays & Collections
Estimated reading: 3 minutes 39 views

🧮 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 / MethodDescription
sizeTotal 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 declarationUse arrayOf() or Array() in Kotlin
Mixing types in an arrayStick to a single type or use Array<Any>
Accessing out-of-bound indexAlways check .size before indexing
Mutating immutable arraysUse val for reference immutability; var to reassign

✅ Best Practices for Arrays in Kotlin

PracticeReason
Use typed arrays for performanceIntArray, DoubleArray, etc., are more efficient
Prefer val for fixed dataPrevents accidental reassignment
Use utility functionsImproves readability and safety
Use .joinToString() for printingGives 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() or typedArrayOf() to create arrays
  • Access elements via index, iterate with for, indices, or forEach
  • Built-in functions like size, first(), and contains() 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – Arrays

Or Copy Link

CONTENTS
Scroll to Top