Kotlin Listcontains Function

The Kotlin List.contains() function returns true if element is found in the list, else false.

Syntax of Listcontains

The syntax of List.contains() function is

list.contains(element)
Parameter Description
element The element which has to be checked if present in this list.

Return Value

Value Scenario
true If element is present in the list.
false If element is not present in the list.

Example 1 Check if List Contains Element

In this example, we will take a list of strings, list1, and a string, element. We will use list.contains() method to check if list1 contains element.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e", "f")
    val element = "e"
    val result = list1.contains(element)
    print("Is element present in list? $result")
}

Output

Is element present in list? true

Example 2 Listcontains Element not in List

In this example, we will take a list of strings, list1, and a string that is not present in the list. We will call list1.contains() and find out the return value when element is not present in the list.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e", "f")
    val element = "m"
    val result = list1.contains(element)
    print("Is element present in list? $result")
}

Output

Is element present in list? false

Conclusion

In this Kotlin Tutorial, we learned how to check if a list contains a specific element, using Kotlin List.contains() function.