Declaring and Initializing Kotlin Lists
Introduces how to declare and initialize lists.
List
Create a list with listOf().
Unlike arrays, whose size is fixed, lists can add and remove elements with .add() and .remove().
However, arrays can change values with nums[1] = 123, while lists cannot change values with nums[1] = 222.
fun main() {
val nums = listOf(1, 2, 3)
val cols = listOf("Red", "Green", "Blue")
for (n in nums) { println(n) }
for (c in cols) { println(c) }
}
Output:
1
2
3
Red
Green
Blue
Key Functions
filter Function
As shown below, you can apply a filter to a list and extract elements that match the even-number condition.
fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println(nums.filter { it % 2 == 0 })
}
Output:
[2, 4, 6, 8, 10]