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.
To use the
Map.isEmptyfunction, you need to import theMapmodule into your program, as shown below.
import scala.collection.mutable.Map
Syntax
map_name.isEmpty
map_nameis the name of theMapobject.
Parameters
The Map.isEmpty function does not require any parameters.
Return value
If the Map object is 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.Mapobject Main extends App {//creating map with valuesval map_1 = scala.collection.mutable.Map(1 -> "Tom",2 -> "Alsvin",3 -> "Eddie")//map_1 elementsprintln("The map_1 elements: " + map_1);println("The map_1 is empty: " + map_1.isEmpty);//empty mapval map_2 = scala.collection.mutable.Map()//map_2 elementsprintln("The map_2 elements: " + map_2);println("The map_2 is empty: " + map_2.isEmpty);}
Explanation
-
The code above creates two
Mapobjects:map_1andmap_2. -
Next, the
isEmptyfunction checks if either of theMapobjects is empty. -
Since
map_1contains key-value pairs, theisEmptyfunction in line returnsfalse. -
However, as
map_2does not contain any key-value pairs, theisEmptyfunction in line returnstrue.