What is the list.contains() method in Scala?
Overview
The list.contains() function in Scala is used to check if a list contains the specific element sent as a parameter.
list.contains() returns true if the list contains that element. Otherwise, it returns false.
Figure 1, below, shows a visual representation of the list.contains() function.
Syntax
list_name.contains(element)
list_nameis the name of the list.
Parameter
The list.contains() function requires an element in order to check that a specific element exists in the list.
Return value
The function returns a Boolean value, i.e., true if a specific element is present in a list or false if it is not present.
Code
The following code shows how to use the list.contains() function in Scala.
object Main extends App {var list = List(1, 3, 4, 2, 0)//list elementsprintln("The list elements: " + list);//element 3println("The list contains element 3: " + list.contains(3));//element 8println("The list contains element 8: " + list.contains(8));}
Explanation
The code example contains:
-
A list with elements
(1, 3, 4, 2, 0), created using theListClass. -
The first
println()on line 5 prints the list as it is. -
The second
println()prints the result oflist.contains(3), i.e.,true, as the list has the element3in it. -
The third
println()prints the result oflist.contains(8), i.e.,false, as the list does not have the element8in it.