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.

Download Code

 
To get an immutable list with all null elements excluded, you can use the listOfNotNull() function.

Download Code

2. Using mutableListOf() function

If we need a resizable list that can expand or shrink, you can use the mutableListOf() function.

Download Code

 
You can also use arrayListOf() function, which returns an ArrayList implementation.

Download Code

3. Using emptyList() function

If you need an empty read-only list, you can use the emptyList() function.

Download Code

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.

Download Code

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.

Download Code

That’s all about initializing a list in Kotlin.