Multiple Approaches to Check if a String Array Contains a Value in Kotlin

Dec 04, 2025 · Programming · 9 views · 7.8

Keywords: Kotlin | Array Operations | Containment Check | contains Operator | Infix Notation

Abstract: This article provides an in-depth exploration of various methods to check if a string array contains a specific value in Kotlin, focusing on the most commonly used contains operator and its infix notation "in", while comparing alternative approaches such as the combination of filter and any. The article analyzes the performance characteristics, code readability, and applicable scenarios of each method, helping developers choose the most suitable implementation based on specific requirements. Through practical code examples and performance comparisons, readers can comprehensively grasp the core concepts and best practices of array operations in Kotlin.

Core Methods: The contains Operator and Infix Notation

The most straightforward way to check if a string array contains a specific value in Kotlin is to use the contains operator. This operator is a built-in function provided by the Kotlin standard library for collection types, specifically designed to check whether a collection contains a specified element. Its basic syntax is as follows:

val array = arrayOf("apple", "banana", "orange")
val containsApple = array.contains("apple") // returns true
val containsGrape = array.contains("grape") // returns false

Kotlin also offers a more elegant infix notation using the in keyword. This syntactic sugar makes the code more concise and readable, especially in conditional statements:

val array = arrayOf("apple", "banana", "orange")
if ("apple" in array) {
    println("Array contains apple")
}
// or using when expression
when {
    "banana" in array -> println("Array contains banana")
    else -> println("Not found")
}

From an implementation perspective, "value" in array is actually compiled to a call to array.contains("value"). This means both approaches are performance-equivalent, employing linear search algorithms with O(n) time complexity. The choice between them primarily depends on coding style and personal preference, but the in operator is generally considered more idiomatic in Kotlin due to its natural language-like expression.

Alternative Approach: Combining filter and any

Beyond the direct use of the contains operator, developers can achieve the same functionality by combining the filter and any functions. As mentioned in the original question:

val array = arrayOf("apple", "banana", "orange")
val containsApple = array.filter { it == "apple" }.any() // returns true

While this method accomplishes the goal, it has significant performance drawbacks. The filter function creates a new list to store all matching elements, even when only needing to know if at least one match exists. This results in unnecessary memory allocation and copying operations, with performance overhead becoming particularly noticeable when dealing with large arrays.

A more optimized approach is to use the any function directly with a predicate:

val array = arrayOf("apple", "banana", "orange")
val containsApple = array.any { it == "apple" } // returns true

This syntax is semantically clearer and performs better, as it returns immediately upon finding the first match, avoiding unnecessary traversal and memory allocation. However, compared to the contains operator, the any syntax is slightly more verbose, especially in scenarios requiring simple equality checks.

Extended Application: Field Checking in Object Arrays

In practical development, we often need to check if an object array contains elements with specific field values. As mentioned in supplementary answers, this can be achieved using the any function with a lambda expression:

data class Fruit(val name: String, val color: String)

val fruits = arrayOf(
    Fruit("apple", "red"),
    Fruit("banana", "yellow"),
    Fruit("orange", "orange")
)

// Check if there's a fruit with name "apple"
val hasApple = fruits.any { it.name == "apple" } // returns true

// Check if there's a fruit with color "green"
val hasGreenFruit = fruits.any { it.color == "green" } // returns false

For such scenarios, the contains operator is no longer applicable, as it only checks for reference equality (using the == operator, which corresponds to the equals method in Kotlin). When containment checks based on field values are needed, the any function offers greater flexibility.

Performance Analysis and Best Practices

When selecting a method for checking array containment, several key factors should be considered:

  1. Code Conciseness: For simple value-type arrays (like string arrays), the in operator provides the most concise syntax, making the code intent immediately clear.
  2. Performance Considerations: All discussed methods employ linear search with O(n) time complexity. For small arrays, performance differences are negligible; but for large arrays, avoid the combination of filter followed by any, as this creates unnecessary intermediate collections.
  3. Type Safety: Kotlin's static type system ensures all methods are type-safe, with the compiler checking type compatibility at compile time.
  4. Readability: The syntax of the in operator most closely resembles natural language, making code easier to understand and maintain.

Based on this analysis, we recommend the following best practices:

Conclusion

Kotlin offers multiple flexible methods for checking array containment, from the most direct contains operator to the more idiomatic in infix notation, and the any function suitable for complex conditions. Understanding the internal mechanisms and applicable scenarios of these methods helps write code that is both efficient and maintainable. In practical development, the most appropriate method should be selected based on specific requirements, balancing code conciseness, performance, and readability to fully leverage the advantages of the Kotlin language.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.