Kotlin – Check if Given Element is present in this List
To check if a specific element is present in this List, call contains()
function on this List object and pass given element as argument to this function.
The Kotlin List.contains() function checks if the list contains specified element and returns a boolean value.
Syntax of List.contains()
The syntax of List.contains() function is
list.contains(element)
Parameter | Description |
---|---|
element | Required. An element, which we would like to check if present in the list. |
Return Value
List.contains() returns true if the element is present in the list, else it returns false.
Example 1: Check if Element is in List
In this example, we will take a list of strings, and a string element. We will check if the element is in the list using List.contains() function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("ab", "bc", "cd")
val element = "bc"
if (list.contains(element)) {
print("Element: $element is present in the list: $list.")
} else {
print("Element: $element is not present in the list: $list.")
}
}
Output
Element: bc is present in the list: [ab, bc, cd].
You may try with an element that is not present in the list. Then the else block will execute, as list.contains() returns false.
Example 2: Kotlin Type interface failed
In this example, we will take a list of strings and the element is of type integer. If we try to call List.contains() with element of type other than the type of list, then the function throws compiler error.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("ab", "bc", "cd")
val element = 52
if (list.contains(element)) {
print("Element: $element is present in the list: $list.")
} else {
print("Element: $element is not present in the list: $list.")
}
}
Output
Error:(4, 14) Kotlin: Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
Conclusion
In this Kotlin Tutorial, we learned how to check if given element is present in this List, using Kotlin List.contains() function.