Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a short if statement

In my code I have this if statement:

if (categoryName == "SomeName1" || categoryName == "SomeName2" || 
    categoryName == "SomeName3" || categoryName == "SomeName4" || 
    categoryName == "SomeName5" || categoryName == "SomeName6") {
    // Do something
}

I was wondering if I could shorten this if. Something like:

if (categoryName == "SomeName1" and "SomeName2" and "SomeName3" ...) {
    // Do something
}

Is there any aproach to do something like this in Kotlin?

like image 585
Ravers Avatar asked Jun 03 '26 22:06

Ravers


1 Answers

You can use a when statement. The syntax kind of looks like what you were asking for:

when (categoryName) {
    "SomeName1", "SomeName2",  "SomeName3", "SomeName4", "SomeName5", "SomeName6" -> // Do something
}
like image 123
Ekeko Avatar answered Jun 05 '26 10:06

Ekeko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!