코틀린의 when 은 자바의 switch 에 해당하는 역할을 할 수 있다.
fun getNum(value: Int) =
when(value) {
1 -> "1"
2 -> "2"
3 -> "3"
4 -> "4"
else -> throw Exception()
}
fun getNum2(value: Int) =
when(value) {
1, 2, 3, 4 -> "1"
5, 6, 7, 8 -> "2"
else -> throw Exception()
}
분기 조건에 상수만 사용할 수 있는 자바의 switch와 달리 코틀린의 when에선 임의의 객체를 허용한다.
fun getSetOf(value1: Int, value2: Int) =
when (setOf(value1, value2)) {
setOf(1, 2) -> "3"
setOf(2, 3) -> "5"
setOf(3, 4) -> "7"
else -> throw Exception()
}
fun getSetOf2(value1: Int, value2: Int) =
when {
(value1 == 1 && value2 == 2) -> "3"
(value1 == 2 && value2 == 3) -> "5"
(value1 == 3 && value2 == 4) -> "7"
else -> throw Exception()
}
when(...) {
"A" -> {
// 코드 1
// 코드 2
}
}