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.

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

Syntax


list_name.contains(element)

list_name is 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 elements
println("The list elements: " + list);
//element 3
println("The list contains element 3: " + list.contains(3));
//element 8
println("The list contains element 8: " + list.contains(8));
}

Explanation

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.

Free Resources