Kotlin List contains()
Syntax & Examples


Syntax of List.contains()

The syntax of List.contains() function is:

abstract fun contains(element: E): Boolean

This contains() function of List checks if the specified element is contained in this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We check if list1 contains the element 'p' using the List contains() function.
  • The result, which is a Boolean value indicating whether 'p' is in list1, is stored in containsP.
  • Finally, we print the value of containsP to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val containsP = list1.contains(&quot;p&quot;);
    print(containsP);
}

Output

true

2 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30.
  • We check if list1 contains the element 20 using the List contains() function.
  • The result, which is a Boolean value indicating whether 20 is in list1, is stored in contains20.
  • Finally, we print the value of contains20 to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val contains20 = list1.contains(20);
    print(contains20);
}

Output

true

Summary

In this Kotlin tutorial, we learned about contains() function of List: the syntax and few working examples with output and detailed explanation for each example.