Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When statement with two variables kotlin

Tags:

kotlin

So i wanna make this when statement with two Integers. I tried to do it this way:

when(row && column) {
     in 0..2 -> end = true;
     else -> {
         end = false;
         println("Invalid move!")
     }
}

but it didnt work. Is there any way to do this? There are obviously many other ways to do this, but i want my code clean and readable, and this would be very helpful to accomplish that.

like image 258
Kris10an Avatar asked Jun 08 '18 20:06

Kris10an


2 Answers

Why don't do it the regulr way?

when {
    row in 0..2 && column in 0..2-> end = true;
    else -> {
        end = false;
        println("Invalid move!")
    }
}
like image 99
Raymond Arteaga Avatar answered Oct 29 '22 08:10

Raymond Arteaga


No this isn't possible. Especially, int && int is no valid syntax.

Alternatively, you could express this code like this:

end = if (setOf(row, column).all { it in 0..2 })
    true
else
    false.also { println("Invalid move!") }

I’m not a big fan of substituting if with when for such basic cases but that’s a matter of taste.

like image 27
s1m0nw1 Avatar answered Oct 29 '22 08:10

s1m0nw1