This article explores different ways to initialize a List of Lists in Kotlin.

1. Using List Constructor

The standard solution to initialize a List of Lists is using the List or MutableList constructor. This is demonstrated below:

Download Code

Output:

[[], [], []]

 
Here’s a slight variation of the above approach to initialize the list with default values:

Download Code

Output:

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

2. Using listOf() function

We can declare a list using the listOf() function. To initialize a List of Lists in a single line, use the listOf() function like below:

Download Code

Output:

[1, 2, 3]
[4, 5, 6]
[6, 7, 8]

 
We can also use the mutableListOf() function to get a mutable list. After getting the mutable instance, we can pass a new list instance to the add() function.

Download Code

Output:

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

3. Using map() function

Another plausible way is to use the map() function to generate a List of Lists, as demonstrated below:

Download Code

Output:

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

That’s all about initializing a List of Lists in Kotlin.