To initialize a list in Kotlin, you can use the listOf
function for a read-only list or the mutableListOf
function for a mutable list.
In this example,
listOf
function to create a read-only list of integers and assign it to the variable readOnlyList
.listOf
function takes the elements as arguments and returns a list containing those elements.fun main() {
val readOnlyList = listOf(1, 2, 3, 4, 5)
println("Read-Only List: $readOnlyList")
}
Read-Only List: [1, 2, 3, 4, 5]
In this example,
mutableListOf
function to create a mutable list of strings and assign it to the variable mutableList
.mutableListOf
function takes the elements as arguments and returns a list containing those elements.add
method.fun main() {
val mutableList = mutableListOf("Apple", "Banana", "Cherry")
mutableList.add("Date")
println("Mutable List: $mutableList")
}
Mutable List: [Apple, Banana, Cherry, Date]
In this tutorial, we learned How to Initialize a List in Kotlin language with well detailed examples.