Eugene Surkov
Eugene Surkov

Reputation: 255

How to simplify multiple equals checks in if condition?

How can I do this easier with Kotlin?

if (translation.equals(TRANSLATION_X) || 
    translation.equals(TRANSLATION_Y) || 
    translation.equals(TRANSLATION_Z)
) {
    return
} else {
    translation = TRANSLATION_X
}

Upvotes: 21

Views: 17379

Answers (3)

Renato
Renato

Reputation: 13710

Another alternative that may be more efficient than a when expression is to use a Set:

val options = setOf(TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z)

if (translation in options) return
else translation = TRANSLATION_X

Upvotes: 20

hotkey
hotkey

Reputation: 148169

First, you can use the structural equality operator ==, which is translated to the .equals(...) calls automatically: translation == TRANSLATION_X instead of translation.equals(TRANSLATION_X).

Then, you can use the when statement:

when (translation) {
    TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z -> return
    else -> translation = TRANSLATION_X
}

Upvotes: 32

user7666746
user7666746

Reputation: 144

A when statement seems appropriated in this situation :

val translation = when( translation ) {
    TRANSLATION_X -> translation
    TRANSLATION_Y -> translation
    TRANSLATION_Z -> translation
    else TRANSLATION_X
}

I think you can also group the three similar cases in one sentence like this :

val translation = when( translation ) {
    TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z -> translation
    else TRANSLATION_X
}

Upvotes: 6

Related Questions