티스토리 뷰

Programming/Kotlin

Kotlin Conditions

Albothyl 2022. 4. 23. 11:44

if

var max = a
if (a < b) max = b

// With else
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

// As expression
val max = if (a > b) a else b

// blocks
val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}

when

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

//-------------- enum
enum class Color {
  RED, GREEN, BLUE
}

when (getColor()) {
    Color.RED -> println("red")
    Color.GREEN -> println("green")
    Color.BLUE -> println("blue")
    // 'else' is not required because all cases are covered
}

when (getColor()) {
  Color.RED -> println("red") // no branches for GREEN and BLUE
  else -> println("not red") // 'else' is required
}

//-------------- expressions
when (x) {
    s.toInt() -> print("s encodes x")
    else -> print("s does not encode x")
}

//-------------- range
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")
}

//-------------- smart cast
fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

//-------------- capture
fun Request.getBody() =
    when (val response = executeRequest()) {
        is Success -> response.body
        is HttpError -> throw HttpException(response.status)
    }

'Programming > Kotlin' 카테고리의 다른 글

Kotlin Null Safety  (0) 2022.04.23
Kotlin Loop  (0) 2022.04.23
Kotlin Operator  (0) 2022.04.23
Kotlin Class  (0) 2022.04.16
Kotlin Visibility Modifiers  (0) 2022.04.16
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함