TIL

Lec 05. 코틀린에서 제어문을 다루는 방법

1. if 문

fun validateScoreIsNotNagative(score: Int) {
  if (score < 0) {
    throw IllegalArgumentException("${score}는 0보다 작을 수 없다.")
  }
}

2. Expression과 Statement

int score = 30 + 40; // 이 연산은 70이라는 하나의 결과가 나오기에 Expression이면서 Statement

String grade = if (score >= 50) { // 컴파일 에러, 자바에선 if-else는 Expression이 아니기 때문
  "Pass";
} else {
  "Fail";
}
fun getPassOrFail(score: Int): String {
  return if (score >= 50) {
    "Pass"
  } else {
    "Fail"
  }
}
fun validateScoreIsNotNagative(score: Int) {
  if (score !in 0..100) {
    throw IllegalArgumentException("${score}는 0부터 100 사이어야 합니다.")
  }
}

3. switch와 when

fun getGradeWithSwitch(score: Int): String {
  return when (score / 10) {
    9 -> "A"
    8 -> "B"
    7 -> "C"
    else -> "D"
  }
}
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이 아닙니다.")
  }
}