What is the Map.isEmpty function in Scala?

The Map.isEmpty function in Scala is used to check if a Map is empty or not.

The following is a visual representation of the Map.isEmpty function.

Visual representation map.isEmpty function

To use the Map.isEmpty function, you need to import the Map module into your program, as shown below.

import scala.collection.mutable.Map

Syntax

map_name.isEmpty

map_name is the name of the Map object.

Parameters

The Map.isEmpty function does not require any parameters.

Return value

If the Map object is emptyi.e., no key-value pairs exist, the Map.isEmpty function returns true. Otherwise, it returns false.

Code

The following code shows how to use the Map.isEmpty function in Scala.

import scala.collection.mutable.Map
object Main extends App {
//creating map with values
val map_1 = scala.collection.mutable.Map(
1 -> "Tom",
2 -> "Alsvin",
3 -> "Eddie"
)
//map_1 elements
println("The map_1 elements: " + map_1);
println("The map_1 is empty: " + map_1.isEmpty);
//empty map
val map_2 = scala.collection.mutable.Map()
//map_2 elements
println("The map_2 elements: " + map_2);
println("The map_2 is empty: " + map_2.isEmpty);
}

Explanation

  • The code above creates two Map objects: map_1 and map_2.

  • Next, the isEmpty function checks if either of the Map objects is empty.

  • Since map_1 contains key-value pairs, the isEmpty function in line 1212 returns false.

  • However, as map_2 does not contain any key-value pairs, the isEmpty function in line 1818 returns true.

Free Resources