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.
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.
You can create empty collections like this:
val occupations = mapOf<String, String>()
val shoppingList = listOf<String>()
val favoriteGenres = setOf<String>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With