Search code examples
androidkotlin

What is the function of emptyList in Kotlin


Why there is such emptyList constructor in Kotlin? It was a immutable List, so there is no way to add or remove its elements and it was empty! So, what is the function of this emptyList?


Solution

  • The emptyList is not a constructor, but a function that returns an immutable empty list implementation.

    The main reason such a function exists is to save allocations. Since emptyList returns the same singleton instance every time it is called, so one can use it in an allocation free manner. An argumentless overload of listOf calls emptyList internally. Note that the very same object is returned regardless of the element type, i.e. emptyList<String>() === emptyList<Int>() is true.

    IMHO emptyList also reads a bit better than listOf when used as e.g. a default parameter value:

    data class Person(val friends:List<Person> = emptyList())