What is the map.contains() method in Scala?

The map.contains() function in Scala checks if a map contains the specific key sent as a parameter. map.contains() returns true if the map contains that key. Otherwise, it returns false.

Figure 1 below shows a visual representation of the map.contains() function:

Figure 1: Visual representation of the map.contains() function

The following module is required in order to use the function: scala.collection.mutable.Map.

Syntax

map_name.contains(key)

map_name is the name of the map.

Parameter

The map.contains() function requires a key in order to check that a specific key-value pair exists in the map.

Return value

The function returns a boolean value, i.e., true if a specific key is present in a map or false if it is not present.

Code

The following code shows how to use the map.contains() function in Scala:

import scala.collection.mutable.Map
object Main extends App {
//creating map with values
val map = scala.collection.mutable.Map(
1 -> "Tom",
2 -> "Alsvin",
3 -> "Eddie"
)
//map_1 elements and length
println("The map elements: " + map);
//key 3
println("The map contains key number 3: " + map.contains(3));
//key 0
println("The map contains key number 0: " + map.contains(0));
}

Free Resources