if
는 자바와 크게 다르지 않다.fun validateScoreIsNotNagative(score: Int) {
if (score < 0) {
throw IllegalArgumentException("${score}는 0보다 작을 수 없다.")
}
}
if-else
는 Statement이지만 Kotlin에선 Expression이다.
int score = 30 + 40; // 이 연산은 70이라는 하나의 결과가 나오기에 Expression이면서 Statement
String grade = if (score >= 50) { // 컴파일 에러, 자바에선 if-else는 Expression이 아니기 때문
"Pass";
} else {
"Fail";
}
if-else
가 Expression이기에 if-else
를 바로 return
할 수도 있다.
fun getPassOrFail(score: Int): String {
return if (score >= 50) {
"Pass"
} else {
"Fail"
}
}
in a .. b
문법을 사용할 수 있다.fun validateScoreIsNotNagative(score: Int) {
if (score !in 0..100) {
throw IllegalArgumentException("${score}는 0부터 100 사이어야 합니다.")
}
}
switch-case
가 사라지고 when
이 등장한다.fun getGradeWithSwitch(score: Int): String {
return when (score / 10) {
9 -> "A"
8 -> "B"
7 -> "C"
else -> "D"
}
}
when
에선 조건부에 다양한 조건으로 분기를 설정할 수 있다.
fun getGradeWithSwitch(score: Int): String { // 조건부에 범위 조건
return when (score) {
in 91..100 -> "A"
in 81..90 -> "B"
in 71..80 -> "C"
else -> "D"
}
}
fun startsWithA(obj: Any): Boolean { // 조건부에 is Type
return when (obj) {
is String -> obj.startsWith("A")
else -> false
}
}
fun judgeNumber(number: Int) { // 조건부에 다중 조건
return when (number) {
1, 0, -1 -> pintln("어디서 많이 본 숫자입니다.")
else -> println("1, 0, -1이 아닙니다.")
}
}
when
은 Enum
혹은 Sealed Class
와 함께 사용할 경우 더 진가를 발휘한다.