Kotlin Map isNullOrEmpty()
Syntax & Examples
Syntax of Map.isNullOrEmpty()
The syntax of Map.isNullOrEmpty() extension function is:
fun <K, V> Map<out K, V>?.isNullOrEmpty(): BooleanThis isNullOrEmpty() extension function of Map returns true if this nullable map is either null or empty.
✐ Examples
1 Check if a non-empty map is null or empty
In this example,
- We create a non-empty map named
map1. - We use the
isNullOrEmptyfunction onmap1. - Since
map1is non-empty, the function returnsfalse. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf("key1" to "value1", "key2" to "value2")
val result1 = map1.isNullOrEmpty()
println(result1)
}Output
false
2 Check if an empty map is null or empty
In this example,
- We create an empty map named
map2. - We use the
isNullOrEmptyfunction onmap2. - Since
map2is empty, the function returnstrue. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = emptyMap<String, Int>()
val result2 = map2.isNullOrEmpty()
println(result2)
}Output
true
3 Check if a nullable map is null or empty
In this example,
- We declare a nullable map
map3and assign it a value ofnull. - We use the
isNullOrEmptyfunction onmap3. - Since
map3isnull, the function returnstrue. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3: Map<String, String>? = null
val result3 = map3.isNullOrEmpty()
println(result3)
}Output
true
Summary
In this Kotlin tutorial, we learned about isNullOrEmpty() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.