Question
How can I check whether an array of strings contains a particular value in Kotlin, similar to Ruby's include? method?
For example, I considered the following approach:
array.filter { it == "value" }.any()
Is there a more direct or idiomatic way to do this?
Short Answer
You will learn Kotlin's idiomatic membership checks for string arrays: the in operator and contains() function. You will also see when to use any { ... } for conditions, why filter().any() is wasteful for a simple lookup, and how string equality works in Kotlin.
Concept
To test whether an array contains an exact value, Kotlin provides two direct options:
"value" in array
array.contains("value")
They mean the same thing. The in form is usually easier to read in a condition.
val fruits = arrayOf("apple", "banana", "orange")
if ("banana" in fruits) {
println("Found it")
}
For strings, Kotlin's == compares content rather than object identity. Therefore, two separate string objects containing the same characters are considered equal.
Your approach works:
array.filter { it == "value" }.any()
However, filter creates a new collection containing all matches, then any() checks whether that new collection is non-empty. If all you need is a yes/no answer, use in, contains(), or any { ... } instead.
Mental Model
Think of an array as a row of labelled drawers.
"banana" in fruitsasks: “Is there a drawer labelledbanana?”fruits.contains("banana")asks the same question in a method-call style.fruits.any { it.startsWith("b") }asks a broader question: “Does any drawer have a label that starts withb?”filter { ... }first gathers every matching drawer into a new box. That is useful when you need the matches themselves, but unnecessary when you only need to know whether one exists.
Syntax and Examples
Use in for an exact membership check:
val roles = arrayOf("admin", "editor", "viewer")
val canEdit = "editor" in roles
println(canEdit) // true
Use contains() when you prefer an explicit function name:
val roles = arrayOf("admin", "editor", "viewer")
println(roles.contains("guest")) // false
Use any { ... } when the check is based on a condition instead of one exact value:
val filenames = arrayOf("report.pdf", "photo.jpg", "notes.txt")
val hasPdf = filenames.any { it.endsWith(".pdf") }
println(hasPdf) // true
any stops as soon as it finds a matching element, so it is appropriate for existence checks.
Step by Step Execution
Consider this code:
val colors = arrayOf("red", "green", "blue")
val wanted = "green"
val exists = wanted in colors
println(exists)
Execution:
colorsis created with three strings:red,green, andblue.wantedstores the stringgreen.wanted in colorschecks the array elements for one equal towanted.reddoes not matchgreen.greenmatches, so Kotlin can stop checking.existsreceivestrue.- The program prints
true.
A conditional search works similarly:
val values = arrayOf("cat", "dog", "elephant")
val hasLongWord = values.any { it.length > 5 }
println(hasLongWord) // true
any tests cat, then dog, then elephant. The last string has more than five characters, so the result is true.
Real World Use Cases
Membership checks appear whenever an application needs to allow, deny, or recognize a known value.
- User roles: check whether a user has an allowed role.
val allowedRoles = arrayOf("admin", "moderator") val allowed = userRole in allowedRoles - File validation: allow only selected extensions.
val allowedExtensions = arrayOf("jpg", "png", "webp") val valid = extension in allowedExtensions - API parameters: verify that a
sortparameter is one of the supported values. - Command-line tools: check whether a supplied command is recognized.
- Data cleaning: determine whether a status belongs to a list of values that should be skipped.
Real Codebase Usage
In production Kotlin code, exact membership checks are commonly paired with validation and early returns.
fun parseSortOrder(input: String): String? {
val supported = setOf("asc", "desc")
if (input !in supported) {
return null
}
return input
}
The !in operator means “is not contained in.” The early return prevents invalid values from reaching later logic.
For a fixed collection of unique allowed values, developers often use a Set:
private val allowedStatuses = setOf("pending", "active", "archived")
fun isAllowedStatus(status: String): Boolean = status in allowedStatuses
For custom rules, use any rather than trying to transform the collection first:
fun hasInternalEmail(emails: List<String>): Boolean {
return emails.any { it.endsWith("@company.example") }
}
Use filter only when later code needs the matching elements:
val imageFiles = filenames.filter { it.endsWith(".png") }
println("Found ${imageFiles.size} PNG files")
Common Mistakes
Creating a filtered collection just to get a Boolean
This is valid but does extra work:
val found = array.filter { it == "value" }.any()
Prefer:
val found = "value" in array
Or, for a predicate:
val found = array.any { it == "value" }
Using === for string contents
=== checks whether two references point to the exact same object. It is usually wrong for comparing string text.
// Avoid for content comparison
val same = first === second
Use ==:
val same = first == second
Expecting case-insensitive matching by default
Membership is case-sensitive:
val values = arrayOf("Admin")
println("admin" in values) // false
For case-insensitive matching, use a predicate:
val exists = values.any { it.equals("admin", ignoreCase = true) }
Forgetting nullable values
An Array<String?> can contain null:
val values: Array<String?> = arrayOf("ready", null)
println(null in values) // true
Be explicit about whether null is a valid value in your application.
Checking the wrong collection type
Array, List, and Set all support in, but their performance characteristics differ. If you repeatedly look up values in a large unique collection, a Set is usually a better fit than an Array or List.
Comparisons
| Approach | Best use | Result | Notes |
|---|---|---|---|
value in array | Exact value membership | Boolean | Idiomatic Kotlin syntax. |
array.contains(value) | Exact value membership | Boolean | Equivalent to in; more explicit. |
array.any { condition } | Condition-based existence check | Boolean | Use for rules such as prefixes, lengths, or case-insensitive comparisons. |
array.filter { condition } | You need all matching values | List<T> | Do not use only to determine whether a match exists. |
set.contains(value) | Frequent lookup in a unique-value collection | Boolean | Often a better data structure for repeated membership checks. |
in is not limited to arrays:
println("a" in listOf("a", "b")) // true
println("a" in setOf("a", "b")) // true
For arrays and lists, searching is generally linear: elements are examined until a match is found or the collection ends. A hash-based set is generally more suitable for many repeated lookups.
Cheat Sheet
// Exact match: recommended
val found = "value" in array
// Exact match: equivalent form
val found = array.contains("value")
// Not contained
val missing = "value" !in array
// Match a rule
val hasLongValue = array.any { it.length > 5 }
// Case-insensitive match
val foundIgnoringCase = array.any {
it.equals("value", ignoreCase = true)
}
// Get every match, rather than only true/false
val matches = array.filter { it == "value" }
Rules to remember:
- Use
==for string content equality. - Use
===only when reference identity is specifically required. inandcontains()are equivalent for membership checks.- Use
any { ... }for a condition. - Avoid
filter(...).any()unless you also need the filtered values.
FAQ
How do I check whether an array contains a string in Kotlin?
Use the in operator:
val exists = "value" in array
You can also write array.contains("value").
Is Kotlin in the same as contains()?
For membership checks, yes. value in collection calls the collection's containment logic and is commonly read as “value is contained in collection.”
Should I use filter().any() to check whether a value exists?
Usually no. It creates a filtered result before checking it. Use value in array for exact values, or array.any { ... } for a condition.
Does Kotlin compare strings by value?
Yes. first == second compares their text contents. Use === only when you need to know whether both variables refer to the same object.
How do I ignore uppercase and lowercase when checking strings?
Use any with equals:
val found = array.any { it.equals("value", ignoreCase = true) }
Can I use in with a Kotlin List or Set?
Yes. It works with Array, List, Set, and many other types that support containment.
When should I choose a Set instead of an Array?
Choose a Set when values are unique and your program performs many membership checks. It expresses that duplicates are not important and is commonly more efficient for lookup.
Mini Project
Description
Build a small command validator for a console-style application. The program receives a command and reports whether it is supported. It demonstrates exact membership checks with in and a condition-based check with any.
Goal
Validate a command against a supported-command list and identify whether it is an administrative command.
Requirements
- Create a collection containing the commands
help,list,create, anddelete. - Store a command to check in a variable.
- Print whether the command is supported.
- Print a separate message when the command is an administrative command.
- Treat
createanddeleteas administrative commands.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Add a Maven Repository URL in Gradle Kotlin DSL (build.gradle.kts)
Learn how to add Maven Central and a custom Maven repository URL in Gradle Kotlin DSL using build.gradle.kts syntax.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.