To create a list of size N in Kotlin, you can use the List
constructor or the MutableList
constructor.
In this example,
List
constructor with the size and a lambda function to create a list of size N, with each element initialized to a default value.fun main() {
val size = 5
val list = List(size) { 0 }
println("List of size $size with default values: $list")
}
List of size 5 with default values: [0, 0, 0, 0, 0]
In this example,
MutableList
constructor with the size and a lambda function to create a mutable list of size N, with each element initialized to a default value.fun main() {
val size = 5
val mutableList = MutableList(size) { "" }
println("MutableList of size $size with default values: $mutableList")
}
MutableList of size 5 with default values: [, , , , ]
In this tutorial, we learned How to create a List of size N in Kotlin language with well detailed examples.