Announcement of empty collections in Kotlin

How can I declare an empty collection for mapOf, listOfand setOfin Kotlin ?

I have declared the variables below:

val occupations = mapOf(Pair("Malcolm", "Captain"), Pair("Kaylee", "Mechanic"))
val shoppingList = listOf("catfish", "water", "tulips", "blue paint")
val favoriteGenres = setOf("Rock", "Classical", "Hip hop") 

I want to check if these collections are empty or not.

+4
source share
2 answers

I want to check if these collections are empty or not.

Why can't you just use the method isEmpty()?

print(occupations.isEmpty())    // >>> false
print(shoppingList.isEmpty())   // >>> false
print(favoriteGenres.isEmpty()) // >>> false

Anyway, if you really want to declare an empty collection, you can do it like this:

val emptyList = listOf<String>()
val emptySet = setOf<String>()
val emptyMap = mapOf<String, String>()

OR

val emptyList = emptyList<String>()
val emptySet = emptySet<String>()
val emptyMap = emptyMap<String, String>()

Let me take a look under the hood. A method listOf()called without arguments has the following implementation:

/** Returns an empty read-only list.  The returned list is serializable (JVM). */
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()

It is easy to see that it simply calls another method - emptyList():

/** Returns an empty read-only list.  The returned list is serializable (JVM). */
public fun <T> emptyList(): List<T> = EmptyList

EmptyList:

internal object EmptyList : List<Nothing>, Serializable, RandomAccess {
    // <...>
}

, , ( @brescia123) : List, , .

+12

:

val occupations = mapOf<String, String>()
val shoppingList = listOf<String>()
val favoriteGenres = setOf<String>()
+3

Source: https://habr.com/ru/post/1679773/


All Articles