Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify multiple equals checks in if condition?

Tags:

kotlin

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
}
like image 410
Eugene Surkov Avatar asked Apr 21 '17 12:04

Eugene Surkov


2 Answers

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
}
like image 182
hotkey Avatar answered Oct 23 '22 08:10

hotkey


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
like image 17
Renato Avatar answered Oct 23 '22 08:10

Renato