Baeldung Pro – Kotlin – NPI EA (cat = Baeldung on Kotlin)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

1. Overview

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.

3. Conclusion

In this short tutorial, we saw how to define mutable collections with no elements.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.