To create a Two-Dimensional List in Kotlin, you can use MutableList or List and initialize it with MutableLists or Lists to represent rows and columns.
In this example,
matrix
to represent the 2D list.fun main() {
val matrix = mutableListOf<MutableList<String>>()
for (i in 0 until 3) {
matrix.add(mutableListOf())
for (j in 0 until 3) {
matrix[i].add("Element $i$j")
}
}
println(matrix)
}
[[Element 00, Element 01, Element 02], [Element 10, Element 11, Element 12], [Element 20, Element 21, Element 22]]
In this example,
matrix
to represent the 2D list.fun main() {
val matrix = mutableListOf<MutableList<Int>>()
for (i in 0 until 3) {
matrix.add(mutableListOf())
for (j in 0 until 3) {
matrix[i].add(i * 3 + j)
}
}
println(matrix)
}
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
In this tutorial, we learned How to create a Two Dimensional List in Kotlin language with well detailed examples.