Language/Kotlin
                
              Kotlin - when expression
                TechNote.kr
                 2018. 7. 23. 23:50
              
              
                    
        728x90
    
    
    
  when은 C언어에서의 switch와 완전히 동일하지는 않지만 상당히 유사하다.
기본적인 해당 구문의 사용 예는 다음과 같다.
when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}
when 구문에서는 condition이 맞는 branch를 찾을 때 까지 순차적으로 확인한다.
만약 조건을 만족하는 branch가 없을 경우 else branch를 수행하게 된다.
각 조건이 하나하나씩 표현될 수도 있지만 아래와 같이 여러 종류의 조건이 comma(,)로 구분되어 표현될 수도 있다.
when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}
또한 일반 constant가 아닌 임의의 expression으로도 조건을 표현할 수 있다.
when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}
혹은 in, !in 으로 표현되는 range나 collection 으로 조건이 표현가능하다.
when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}
is, !is로 특정 type여부를 판단하는 조건으로 표현 가능하기도 하다.
fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}
when은 if-else 를 대체할 수도 있다. 별다른 argument가 주어지지 않았을 경우 각 branch condition은 boolean expression 으로 조건 만족여부를 판단할 수 있다.
when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}
728x90