1 분 소요

조건문 작성하기

if 문 예시 기본 예시

fun main() {
    val trafficLightColor = "Yellow"

    if (trafficLightColor == "Red") {
        println("Stop")
    } else if (trafficLightColor == "Yellow") {
        println("Slow")
    } else {
        println("Go")
    }
}

When 문 사용하기

스위치 문 과 유사해보인다

fun main() {
    val trafficLightColor = "Yellow"

    when (trafficLightColor) {
        "Red" -> println("Stop")
        "Yellow" -> println("Slow")
        "Green" -> println("Go")
        else -> println("Invalid traffic-light color")
    }
}

여러조건에 쉼표 사용

여러개의 조건이 겹치는 경우 , 을 사용하여 줄일 수 있다

fun main() {
    val x = 3

    when (x) {
        2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
        else -> println("x isn't a prime number between 1 and 10.")
    }
}

여러 조건에 in 키워드 사용

fun main() {
    val x = 3

    when (x) {
        2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
        in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
        else -> println("x isn't a prime number between 1 and 10.")
    }
}

is 키워드를 사용하여 데이터 유형 확인

fun main() {
    val x: Any = 20

    when (x) {
        2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
        in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
        is Int -> println("x is an integer number, but not between 1 and 10.")
        else -> println("x isn't an integer number.")
    }
}

if문을 표현식 전환

if 문 결과를 변수에 넣을 수 있다.

fun main() {
    val trafficLightColor = "Black"

    val message =
      if (trafficLightColor == "Red") "Stop"
      else if (trafficLightColor == "Yellow") "Slow"
      else if (trafficLightColor == "Green") "Go"
      else "Invalid traffic-light color"

    println(message)
}

요약

요약

  1. Kotlin에서는 if/else 또는 when 조건문을 사용하여 브랜치를 실행할 수 있습니다.
  2. if/else 조건문에서 if 브랜치 본문은 if 브랜치 조건 내의 불리언 표현식이 true 값을 반환할 때만 실행됩니다.
  3. if/else 조건문의 후속 else if 브랜치는 이전 if 또는 else if 브랜치에서 false 값을 반환할 때만 실행됩니다.
  4. if/else 조건문의 마지막 else 브랜치는 이전 모든 if 또는 else if 브랜치에서 false 값을 반환하는 경우에만 실행됩니다.
  5. 브랜치가 3개 이상인 경우 if/else 조건문 대신 when 조건문을 사용하는 것이 좋습니다.
  6. 쉼표(,), in 범위, is 키워드를 사용하여 when 조건문에서 좀 더 복잡한 조건을 작성할 수 있습니다.
  7. if/else 및 when 조건문은 문 또는 표현식으로 사용할 수 있습니다

자료 출처

https://developer.android.com/codelabs/basic-android-kotlin-compose-conditionals?hl=ko&continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-2-pathway-1%3Fhl%3Dko%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-conditionals#0

댓글남기기