Initialize a list in Kotlin
This article explores different ways to initialize a list in Kotlin in a single line.
1. Using listOf() function
The listOf() function returns an immutable list of the given elements, which does not permit the addition or removal of elements. This is similar to Arrays.asList() function in Java.
|
1 2 3 4 |
fun main() { val immutableList: List<Int> = listOf(4, 2, 5, 4, 1) println(immutableList) } |
To get an immutable list with all null elements excluded, you can use the listOfNotNull() function.
|
1 2 3 4 |
fun main() { val list: List<Int> = listOfNotNull(4, 2, 5, 4, null, 1) println(list) } |
2. Using mutableListOf() function
If we need a resizable list that can expand or shrink, you can use the mutableListOf() function.
|
1 2 3 4 |
fun main() { val mutableList: MutableList<Int> = mutableListOf(4, 2, 5, 4, 1) println(mutableList) } |
You can also use arrayListOf() function, which returns an ArrayList implementation.
|
1 2 3 4 |
fun main() { val mutableList: MutableList<Int> = arrayListOf(4, 2, 5, 4, 1) println(mutableList) } |
3. Using emptyList() function
If you need an empty read-only list, you can use the emptyList() function.
|
1 2 3 4 |
fun main() { val emptyList: List<Int> = emptyList() println(emptyList) } |
4. Using Builder functions
Another plausible way is to use builder functions for collections. To get a read-only list, as a result, you can use the buildList, which takes a lambda with a receiver as an argument.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val initial = listOf(1, 3, 5, 7) val ints = buildList { add(0) initial.mapTo(this) { it + 1 } } println(ints) // [0, 2, 4, 6, 8] } |
5. Using Double Brace Initialization
Finally, you can use Double Brace Initialization, which creates an anonymous inner class with just an instance initializer in it.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val mutableList: MutableList<Int> = object : ArrayList<Int>() { init { add(1) add(2) add(3) } } println(mutableList) } |
That’s all about initializing a 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 :)