Initialize an empty list in Kotlin
This article explores different ways to initialize an empty List in Kotlin.
There are several ways to initialize an empty list, as discussed below:
1. Using listOf() function
If you need an immutable empty list instance, you can use the listOf() function, as shown below:
|
1 2 3 4 5 |
fun main() { val list : List<Int> = listOf() println(list) // [] } |
The declaration can be further shortened to:
|
1 2 3 4 5 |
fun main() { val list = listOf<Int>() println(list) // [] } |
2. Using mutableListOf() function
To get a mutable list, you should use the mutableListOf() function.
|
1 2 3 4 5 |
fun main() { val mutableList : MutableList<Int> = mutableListOf() println(mutableList) // [] } |
This can be shortened to:
|
1 2 3 4 5 |
fun main() { val mutableList = mutableListOf<Int>() println(mutableList) // [] } |
3. Using arrayListOf() function
If you need an ArrayList implementation of list, consider using the arrayListOf() function.
|
1 2 3 4 5 |
fun main() { val arrayList : ArrayList<Int> = arrayListOf() println(arrayList) // [] } |
Alternatively, you can write it as following to improve readability:
|
1 2 3 4 5 |
fun main() { val arrayList = arrayListOf<Int>() println(arrayList) // [] } |
4. Using ArrayList Constructor
You can use the ArrayList constructor to get an empty ArrayList instance of the List interface.
|
1 2 3 4 5 |
fun main() { val arrayList : ArrayList<Int> = ArrayList() println(arrayList) // [] } |
Similar to the previous approach, we can rewrite this as:
|
1 2 3 4 5 |
fun main() { val arrayList = ArrayList<Int>() println(arrayList) // [] } |
5. Using LinkedList Constructor
Finally, if you need a LinkedList implementation of the List interface, you can use the LinkedList constructor to get an empty mutable instance of a linked list.
|
1 2 3 4 5 6 7 |
import java.util.LinkedList fun main() { val linkedList : LinkedList<Int> = LinkedList() println(linkedList) // [] } |
This is equivalent to writing:
|
1 2 3 4 5 6 7 |
import java.util.LinkedList fun main() { val linkedList = LinkedList<Int>() println(linkedList) // [] } |
That’s all about initializing an empty list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)