Kotlin Array contains()

Kotlin Array contains()

In Kotlin, the Array contains() function is used to check if this array contains a specified element. It returns true if the element is found in the array, and false otherwise.

This function is handy when you need to determine whether a particular element exists in an array.

In this tutorial, we’ll explore the syntax of the contains() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the contains() function is straightforward:

fun <T> Array<out T>.contains(element: T): Boolean

where

ParameterDescription
elementA value to search for in the array.
Parameters of Array contains() function

Examples

1. Using contains() to Check for a Specific Element

In this example, we’ll use contains() to check if a specific element exists in an array of numbers.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)
    val searchElement = 30

    // Using contains() to check if the array contains the search element
    val containsElement = numbersArray.contains(searchElement)

    // Printing the original array and the result
    println("Numbers: ${numbersArray.joinToString(", ")}")
    println("Array contains $searchElement: $containsElement")
}

Output

Numbers: 10, 20, 30, 40, 50
Array contains 30: true

2. Using contains() to Check for a Specific String

In this example, we’ll use contains() to check if a specific String exists in an array of words.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
    val searchWord = "orange"
    
    // Using contains() to check if the array contains the search word
    val containsWord = wordsArray.contains(searchWord)
    
    // Printing the original array and the result
    println("Words: ${wordsArray.joinToString(", ")}")
    println("Array contains '$searchWord': $containsWord")
}

Output

Words: apple, banana, orange, grape, kiwi
Array contains 'orange': true

In this example, the contains() function is used to check if the array of words contains a specific String. The original array, the search word, and the result are printed to the console.

Summary

In this tutorial, we’ve covered the contains() function in Kotlin arrays, its syntax, and how to use it to check if an array contains a specified element.