How to Check if List Contains Element in Kotlin
In Kotlin, you can check if a list contains an element using the
contains() function or the in keyword. Both return a Boolean value indicating if the element is present in the list.Syntax
The two common ways to check if a list contains an element are:
list.contains(element): Calls thecontains()function on the list.element in list: Uses theinkeyword for a more readable check.
Both return true if the element is found, otherwise false.
kotlin
val list = listOf("apple", "banana", "cherry") // Using contains() val hasBanana = list.contains("banana") // Using 'in' keyword val hasOrange = "orange" in list
Example
This example shows how to check if a list contains certain fruits using both contains() and in. It prints the results to the console.
kotlin
fun main() {
val fruits = listOf("apple", "banana", "cherry")
if (fruits.contains("banana")) {
println("Banana is in the list.")
} else {
println("Banana is not in the list.")
}
if ("orange" in fruits) {
println("Orange is in the list.")
} else {
println("Orange is not in the list.")
}
}Output
Banana is in the list.
Orange is not in the list.
Common Pitfalls
Some common mistakes when checking list membership include:
- Using
==to compare the whole list instead of checking elements. - Forgetting that
contains()andinare case-sensitive for strings. - Trying to check for an element in a
nulllist without safe calls.
Always ensure the list is not null or use safe calls like list?.contains(element).
kotlin
val list: List<String>? = null // Unsafe call - will cause error if list is null // val hasApple = list.contains("apple") // Error // Safe call to avoid error val hasAppleSafe = list?.contains("apple") ?: false
Quick Reference
| Method | Description | Example |
|---|---|---|
| contains() | Checks if list contains element | list.contains("item") |
| in keyword | Checks if element is in list | "item" in list |
| Safe call | Avoids null pointer when list may be null | list?.contains("item") ?: false |
Key Takeaways
Use
contains() or in keyword to check if a list contains an element.Both methods return a Boolean:
true if found, false otherwise.Remember that string checks are case-sensitive.
Use safe calls to avoid errors when the list might be null.
Avoid comparing the whole list with
== when checking for an element.