I've got an input
into my system, current a current state
, and a previous_states
. My first direction of thought would be to use a when
statement, but Kotlin doesn't support using multiple variables in there:
when (input, state, previous_states) {
(KeyPower, PowerOff, matched) -> ...
(KeyPower, PowerOn, matched) -> ...
(KeyMenu, PowerOff, listOf(MainView, _)) -> ...
}
Is just a syntax error. Is there a workaround for this / an entirely different approach?
CodePudding user response:
Not checking all parameters
It is possible using when
, but note that you need to add necessary 'else' branch:
fun getDescription(color: String, shape: String, size: String) : String {
return when {
(color == "red" && shape == "square" && size == "small") -> "You have a small red square"
(color == "red" && shape == "square" && size == "large") -> "You have a large red square"
(color == "blue" && shape == "triangle") -> "You have a blue triangle"
else -> "undefined"
}
}
You can also throw an exception on the else branch
else -> throw IllegalStateException("Invalid input")
Always checking all given parameters
If you always want to check the same number of parameters, you can also use the to
operator:
fun getDescription(color: String, shape: String, size: String): String {
return when (color to shape to size) {
("red" to "square" to "small") -> "You have a small red square"
("red" to "square" to "large") -> "You have a large red square"
("blue" to "triangle" to "small") -> "You have a small blue triangle"
else -> "undefined"
}
}
"red" to "square" to "large"
is of type Pair<Pair<String, String>, String>
and therefore incompatible to be compared with e.g. "blue" to "triangle"
which is of type Pair<String, String>
CodePudding user response:
You can use a when
in this case, but you will have to wrap the three independent var
s/val
s in a Triple
.
Here's an example that uses String
s, because I don't know the types of your var
s/val
s:
fun main() {
val input = "KeyPower"
val state = "PowerOn"
val previous_states = "matched"
when (Triple(input, state, previous_states)) {
Triple("KeyPower", "PowerOff", "matched") -> println("Power, Off, matched")
Triple("KeyPower", "PowerOn", "matched") -> println("Power, On, matched")
Triple("KeyMenu", "PowerOff", "matched") -> println("Menu, Off, matched")
else -> println("no match")
}
}
Output:
Power, On, matched
The when
statement requires a single object, it seems…