반응형
조건문을 다루는 방법
if문
fun validateScoreIsNotNegative(score: Int) {
if (score !in 0..100) {
throw IllegalArgumentException("${score}는 의 범위는 0부터 100입니다.")
}
}
- if, else if, else문 모두 자바와 동일하다.
Expression과 Statement
fun getGrade(score: Int): String {
return if (score >= 90) {
"A"
} else if (score >= 80) {
"B"
} else if (score >= 70) {
"C"
} else {
"F"
}
}
Statement
: 프로그램의 문장, 하나의 값으로 도출되지 않는다.Expression
: 하나의 값으로 도출되는 문장- 자바에서
if/else
문은Statement
이다. - 하지만 코틀린에서
if/else
문은Expression
으로 취급되기 때문에if/else
문 그대로를 return할 수 있다.- 그래서 코틀린에서는 자바에 존재하는 3항연산자가 없다.
Switch와 When
fun getGradeWithSwitch(score: Int): String {
/*
return when (score / 10) {
9 -> "A"
8 -> "B"
7 -> "C"
else -> "D"
}
*/
// in을 이용한 경우
return when (score) {
in 90..99 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "D"
}
}
- Java의 switch는 Kotlin에서 when으로 대체되었고, when은 더 강력한 기능을 갖는다.
- when에는 어떠한 expression이라도 들어갈 수 있다.
- 아래와 같은 when 사용도 가능하다.
fun startsWithA(obj: Any): Boolean {
return when (obj) {
is String -> obj.startsWith("A")
else -> false
}
}
fun judgeNumber(number: Int) {
when (number) {
1, 0, -1 -> println("어디서 많이 본 숫자입니다.")
else -> println("1, 0, -1이 아닙니다.")
}
}
fun judgeNumber2(number: Int) {
when {
number == 0 -> println("주어진 숫자는 0입니다.")
number % 2 == 0 -> println("주어진 숫자는 짝수입니다.")
else -> println("주어진 숫자는 홀수입니다.")
}
}
- when은 Enum Class 혹은 Sealed Class와 함께 사용할 경우, 더욱더 진가를 발휘할 수 있다.
반응형
'Java & Kotlin > Kotlin' 카테고리의 다른 글
[Kotlin] 함수를 다루는 방법 (0) | 2022.07.06 |
---|---|
[Kotlin] 예외를 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 반복문을 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 연산자를 다루는 방법 (0) | 2022.07.05 |
[Kotlin] Type을 다루는 방법 (0) | 2022.07.05 |
[Kotlin] null을 다루는 방법 (0) | 2022.07.05 |