In this quick tutorial, we’re going to see how we can initialize mutable lists, maps, and sets with no elements.
2. Empty Mutable Collections
In Kotlin, initializing a non-empty collection with a few elements is easy. For instance, here we’re initializing a MutableSet with two Strings:
val colors = mutableSetOf("Red", "Green")
As shown above, the compiler will infer the set component type from the passed elements. After initialization, we can add more elements, too:
colors += "Blue"
On the other hand, to initialize a MutableSet with no elements, we should somehow pass the generic type information. Otherwise, the compiler won’t be able to infer the component type. For instance, to initialize an empty MutableSet:
val colorSet = mutableSetOf<String>()
Here, we’re passing the generic type information to the function itself. Moreover, we can declare the type annotations explicitly to achieve the same thing:
val colorSetTagged: MutableSet<String> = mutableSetOf()
Similarly, we can define empty mutable lists and maps, too:
val map = mutableMapOf<String, String>()
val list = mutableListOf<String>()
Again, we can use the explicit type annotations:
val mapTagged: MutableMap<String, String> = mutableMapOf()
val listTagged: MutableList<String> = mutableListOf()
We don’t need to pass the type information to functions when we declare variable types explicitly.
In this short tutorial, we saw how to define mutable collections with no elements.
As usual, all the examples are available over on GitHub.