Kotlin List - Contains() Function



The Kotlin List contains() function is used to check whether the specified element is present in the List. It returns true if the list element is equal to the argument of this function.

Here, are some use cases of the contains():

  • Checking element presence in a List.
  • Validating the user input.
  • Conditional execution based on presence.

Syntax

Following is the syntax of Kotlin List contains() function −

List.contains(element: T)

Parameters

This function accepts as a parameter an element that needs to be checked.

Return value

This function returns true if an element is found in the list. Otherwise, return false.

Example 1: Checking Element Presence in a List.

Let's see a basic example of the contains() function to verify if an element exists in a list.

fun main(args: Array<String>) {
   val flowers = listOf("Daisy", "Lotus", "Rose")
   println(flowers.contains("Lotus"))
   println(flowers.contains("Daisy"))
}

Output

Following is the output −

true
true

Example 2: Validating User Input

The following example uses the contains() function to validate the user input −

fun main(args: Array<String>) {
   val options = listOf("Yes", "No", "Maybe")
   val userInput = "Yes"
   if (options.contains(userInput)) {
      println("Valid input")
   } else {
      println("Invalid input")
   }
}

Output

Following is the output −

Valid input

Example 3: Conditional Execution Based on Presence

This is another example of contains() function. It execute specific logic if an element exists in a list −

fun main(args: Array<String>) {
   val inventory = listOf("Sword", "Shield", "Potion")
   if (inventory.contains("Potion")) {
      println("You have a Potion to heal yourself.")
   } else {
      println("No healing items available.")
   }
}

Output

Following is the output −

You have a Potion to heal yourself.
kotlin_lists.htm
Advertisements