yaugenka
yaugenka

Reputation: 2861

How to compare a value to several other values in one line in Kotlin

Is there a better alternative to this expression in Kotlin: a == b || a == c

I'm looking for something like a == b || c or a.equals(b, c)

Upvotes: 17

Views: 7093

Answers (5)

squirrel
squirrel

Reputation: 5488

I defined a few helper functions:

inline fun <T> T.isAnyOf(a: T, b: T) = this == a || this == b
inline fun <T> T.isAnyOf(a: T, b: T, c: T) = this == a || this == b || this == c

inline fun <T> T.isNotAnyOf(a: T, b: T) = !isAnyOf(a, b)
inline fun <T> T.isNotAnyOf(a: T, b: T, c: T) = !isAnyOf(a, b, c)

Which can be used like this:

if ("word".isAnyOf("list", "of", "words")) { ... }

Upvotes: -1

theblitz
theblitz

Reputation: 6881

Another option (which I personally prefer) is to create an extension function:

fun Any.equalsAny(vararg values: Any): Boolean {
    return this in values
}

Usage example:

val result1 =  20.equalsAny(10, 20, 30)               // Returns true
val result2 =  "ABC".equalsAny(10, 20, 30, 99 , 178)  // Returns false
val result3 =  "ABC".equalsAny("ABC", "XYD", "123")   // Returns true
val result4 =  "ABC".equalsAny("xxx", "XYD", "123")   // Returns false

You can even mix types and it works perfectly:

val a = 1
val b = "10"
val c = true
val search = 999
val search2 = false
val result5 = search.equalsAny(a, b, c)               // Returns false
val result6 = search2.equalsAny(a, b, c, 872, false)  // Returns true

Upvotes: 8

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You can use when as

when(a){
    b,c -> println("match") // match either b or c
    else -> println("no match") // in case of no match
}

Additionally, you can use in with range like

when(number){
    100,200 -> println(" 100 or 200 ")
    in 1..5 -> println("in range") // between 1 - 5
    !in 6..10 -> println("not in range") // not between 6 - 10
    else -> println("no match")
}

You can also use multiple custom enum values as

// often used to represent API/process status etc
when(Status.ERROR){
    in listOf(Status.ERROR, Status.EXCEPTION) -> println("Something when wrong") 
    else -> println("Success")
}

enum class Status{
    SUCCESS, ERROR, EXCEPTION
}

Upvotes: 11

forpas
forpas

Reputation: 164089

I think the simplest way is with the in operator:

a in listOf(b, c)

you can include as many items as you want inside the list.

Upvotes: 29

Willi Mentzel
Willi Mentzel

Reputation: 29844

You could put the values in a list and use any:

listOf(b, c).any { it == a }

This becomes especially handy if you have a lot of values to compare to.


Just in case you need it for and too:

a == b && a == c would translate to listOf(b, c).all { it == a }

Upvotes: 2

Related Questions