Arrays in Kotlin
📌 Arrays in Kotlin
In Kotlin, an Array is a collection of fixed-size, ordered data of the same type. Arrays are widely used to store multiple values in a single variable.
✅ Creating Arrays in Kotlin
1. Using arrayOf()
val intArray = intArrayOf(1, 2, 3)val doubleArray = doubleArrayOf(1.1, 2.2, 3.3)val charArray = charArrayOf('A', 'B', 'C')
3. Using Array Constructor
// Creates an array of size 5 with values as the index multiplied by 2val array = Array(5) { it * 2 }println(array.joinToString()) // Output: 0, 2, 4, 6, 8
✅ Accessing Elements in an Array
You can access array elements using:
Indexing: (Starts from
0)get()andset()functions
val fruits = arrayOf("Apple", "Banana", "Cherry")// Using Indexprintln(fruits[1]) // Output: Banana// Using get() functionprintln(fruits.get(2)) // Output: Cherry// Updating value using set() functionfruits.set(1, "Mango")println(fruits[1]) // Output: Mango
✅ Array Properties and Functions
size→ Returns the number of elements in the array.first()→ Returns the first element.last()→ Returns the last element.contains()→ Checks if an element exists in the array.indexOf()→ Returns the index of an element or-1if not found.
val numbers = arrayOf(10, 20, 30, 40, 50)println("Size: ${numbers.size}") val names = arrayOf("John", "Emma", "Alex")for (name in names) { println(name)}
2. Using forEach
names.forEach { println(it) }
3. Using Indices
for (index in names.indices) { println("Index $index: ${names[index]}")}
✅ Multidimensional Arrays
Kotlin supports 2D and 3D Arrays using the Array class.
// 2D Array (3x3 Matrix)val matrix = Array(3) { Array(3) { 0 } }matrix[0][1] = 5println(matrix[0][1]) // Output: 5
✅ Conclusion
Use
arrayOf()for general-purpose arrays.Use
intArrayOf(),charArrayOf(), etc., for primitive types.Arrays are fixed in size and cannot be resized. For dynamic collections, use Lists instead.