when
//java
int x = 1;
switch(x) {
case 1 :
System.out.println(1);
break;
case 2 :
System.out.println(2);
break;
default :
System.out.println(default);
break;
}//kotlin
val x = 1
when {
x == 1 -> print("x == 1")
x == 2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
//위에 조건을 줄여서 표기도 가능하다
// 1.
when(x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
//2.
when(x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
//3.
val s = "1"
val x = 1
when(x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
fun parseInt(value: String): Int = 1
//4.
val x = 129
val validNumbers = 100..120
//when의 조건에 표현식이 들어갈 수 있다.
when(x) {
in 1..10 -> println("x is in the range")
in validNumbers -> println("x is valid")
!in 10..20 -> println("x is outSide the range")
else -> println("none of the above")
}Last updated