Sure! Arrays in Kotlin are used to store multiple values of the same data type in a single variable. Here's a simple explanation with an example:
You can declare an array using the arrayOf()
function, specifying the values within the parentheses.
Example
val numbers = arrayOf(1, 2, 3, 4, 5)
You can access individual elements of the array using square brackets []
and the index of the element (indexes start from 0).
Example
val firstNumber = numbers[0] // Accessing the first element
val secondNumber = numbers[1] // Accessing the second element
You can modify elements of the array by assigning a new value to a specific index.
Example
numbers[2] = 10 // Changing the value of the third element to 10
You can get the length of the array using the size
property.
Example
<h3>Array Length</h3>
<p>You can get the length of the array using the <code>size</code> property.</p>
You can iterate through the elements of an array using loops like for
.
Example
for (number in numbers) {
println(number)
}
Arrays can hold elements of different data types using generics.
Example
val mixedArray = arrayOf("Kotlin", 10, 3.14, true)
Arrays are useful for storing collections of data in Kotlin. They allow you to access and manipulate individual elements efficiently, making them essential for many programming tasks.