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.
list_name.contains(element)
list_name
is the name of the list.
The list.contains()
function requires an element
in order to check that a specific element exists in the list.
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.
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));}
The code example contains:
A list with elements (1, 3, 4, 2, 0)
, created using the List
Class.
The first println()
on line 5 prints the list as it is.
The second println()
prints the result of list.contains(3)
, i.e., true
, as the list has the element 3
in it.
The third println()
prints the result of list.contains(8)
, i.e., false
, as the list does not have the element 8
in it.