Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring empty collections in Kotlin

Tags:

kotlin

How can i declare an empty collection for mapOf,listOf and setOf in Kotlin?

I have declared below variables:

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 is these collection are empty or not.

like image 288
Rohit Parmar Avatar asked Jun 21 '17 07:06

Rohit Parmar


2 Answers

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

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

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's take a look under the hood. Method listOf() called with no 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's 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

that returns an internal object named EmptyList:

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

So the summary is that (as @brescia123 said) these methods do exactly the same thing: both of them return an empty immutable List and it's up to you to decide which one to use.

like image 177
Alexander Romanov Avatar answered Nov 09 '22 15:11

Alexander Romanov


You can create empty collections like this:

val occupations = mapOf<String, String>()
val shoppingList = listOf<String>()
val favoriteGenres = setOf<String>()
like image 20
zsmb13 Avatar answered Nov 09 '22 13:11

zsmb13