Kotlin Arrays
An array is a collection of similar data types in Kotlin that stores values in consecutive memory addresses.
Syntax
To declare an array in Kotlin, use the following syntax:
var arrayName = arrayOf(element1, element2, element3, ...)
You can also declare an array of a specified size and initialize it later:
var arrayName = Array(size){0}
Example
fun main(args: Array<String>) {
var numbers = arrayOf(1, 2, 3, 4, 5) // array of integers
var names = arrayOf("John", "Mary", "David") // array of strings
// accessing array elements
println(numbers[0]) // prints 1
println(names[2]) // prints David
}
Output
1
David
Explanation
In the above example, we have created two arrays. The first array contains integers and the second array contains strings. We have accessed the first element of the numbers
array and the third element of the names
array using the index operator.
Use
Arrays in Kotlin are used to store a fixed number of elements of the same data type. They are commonly used in loops and algorithms.
Important Points
- Array indices in Kotlin start from 0.
- Arrays in Kotlin are mutable, meaning you can change the values of their elements.
- The size of an array in Kotlin is fixed at runtime and cannot be changed once it is declared.
Summary
Arrays are an essential data structure in Kotlin that allows you to store a collection of similar data types. You can create arrays using the arrayOf
function or the Array
class, and access their elements using the index operator. Arrays are mutable and have a fixed size at runtime.