Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Arrays are fundamental data structures that can store multiple values of the same type. In Kotlin, arrays are represented by the Array
class, and the language provides dedicated functions and constructs to work with them.
Using the arrayOf
function: The simplest way to create an array.
val numbers = arrayOf(1, 2, 3, 4, 5) val names = arrayOf("Alice", "Bob", "Charlie")
Using constructors: To create an array of a given size and initialize it with the specified lambda.
val squares = Array(5) { i -> (i + 1) * (i + 1) } // [1, 4, 9, 16, 25]
Specialized array types: Kotlin has specialized classes for primitive arrays to avoid boxing overhead: IntArray
, DoubleArray
, CharArray
, etc.
val intArray = intArrayOf(1, 2, 3) val charArray = charArrayOf('a', 'b', 'c')
You can use indices to access or modify elements in an array:
val arr = arrayOf(1, 2, 3) println(arr[0]) // Outputs: 1 arr[1] = 5 println(arr[1]) // Outputs: 5
You can use standard loops or forEach
:
val fruits = arrayOf("Apple", "Banana", "Cherry") for (fruit in fruits) { println(fruit) } fruits.forEach { println(it) }
With indices:
for (index in fruits.indices) { println("fruits[$index] = ${fruits[index]}") }
size: Gives the size of the array.
println(fruits.size) // Outputs: 3
lastIndex: Gives the last valid index of the array.
println(fruits.lastIndex) // Outputs: 2
first() and last(): Retrieves the first and the last element.
println(fruits.first()) // Outputs: Apple println(fruits.last()) // Outputs: Cherry
indexOf(): Finds the index of an element.
println(fruits.indexOf("Banana")) // Outputs: 1
You can create arrays of arrays:
val matrix = arrayOf( arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9) ) println(matrix[1][2]) // Outputs: 6
val nums = arrayOf(3, 7, 1, 6, 4) nums.sort() println(nums.joinToString()) // Outputs: 1, 3, 4, 6, 7 val evens = nums.filter { it % 2 == 0 } println(evens) // Outputs: [4, 6]
Arrays in Kotlin provide an intuitive and comprehensive way to manage collections of items. While they are very flexible and efficient for many tasks, remember that in certain situations, other collections (like List
, Set
, or Map
) might be more appropriate. It's always essential to pick the right data structure for your specific needs.
How to create arrays in Kotlin:
Arrays in Kotlin can be created using the arrayOf()
function.
val numbers = arrayOf(1, 2, 3, 4, 5)
Kotlin array initialization: Arrays can also be initialized using constructor syntax:
val animals = Array(3) { "Animal $it" }
Accessing elements in Kotlin arrays: Elements in arrays can be accessed using index notation.
val firstAnimal = animals[0]
Kotlin array size and indices:
You can obtain the size of an array using the size
property, and indices start from 0.
val arraySize = numbers.size val lastIndex = numbers.size - 1
Array manipulation in Kotlin: Arrays can be modified by assigning new values to elements.
numbers[2] = 10
Working with primitive arrays in Kotlin:
Kotlin provides specialized classes like IntArray
, DoubleArray
, etc., for working with primitive types efficiently.
val intArray = IntArray(5) intArray[0] = 42
Iterating over arrays in Kotlin:
Arrays can be iterated using various constructs, such as loops or the forEach
function.
for (number in numbers) { println(number) }
Multidimensional arrays in Kotlin: Kotlin supports multidimensional arrays using nested arrays.
val matrix = Array(3) { IntArray(3) }
Kotlin array of objects: Arrays can hold objects of any type, including custom classes.
data class Person(val name: String) val people = arrayOf(Person("Alice"), Person("Bob"))
Copying arrays in Kotlin:
Arrays can be copied using functions like copyOf
or copyOfRange
.
val copyOfNumbers = numbers.copyOf()
Array functions and methods in Kotlin:
Arrays provide various functions and methods for common operations, such as sum()
, average()
, max()
, min()
, etc.
val sum = numbers.sum()
Filtering and transforming arrays in Kotlin:
You can filter and transform arrays using functions like filter
, map
, flatMap
, etc.
val evenNumbers = numbers.filter { it % 2 == 0 }
Sorting arrays in Kotlin:
Arrays can be sorted using functions like sort
, sorted
, or custom sorting logic.
val sortedNumbers = numbers.sorted()
Nullability and arrays in Kotlin:
Arrays can hold nullable elements, and you can use the safe call operator (?.
) to handle null values.
val nullableArray: Array<Int?> = arrayOf(1, null, 3)