Develop!/Kotlin

when in kotlin

체리필터 2023. 8. 23. 10:27
728x90
반응형

kotlin에서도 when 문을 쓸 수 있다. 다음은 독일어의 기수를 서수로 바꿔주는 when 문이다.

val numbers = mapOf(
    1 to "eins", 2 to "zwei", 3 to "drei",
    4 to "vier", 5 to "fuenf", 6 to "sechs",
    7 to "sieben", 8 to "acht", 9 to "neun",
    10 to "zehn", 11 to "elf", 12 to "zwoelf",
    13 to "dreizehn", 14 to "vierzehn",
    15 to "fuenfzehn", 16 to "sechzehn",
    17 to "siebzehn", 18 to "achtzehn",
    19 to "neunzehn", 20 to "zwanzig"
)

fun ordinal(i: Int): String =
    when (i) {
        1 -> "erste"
        3 -> "dritte"
        7 -> "siebte"
        8 -> "achte"
        20 -> "zwanzigste"
        else -> numbers.get(i) + "te"
    }

fun germanOrdinal() {
    println(ordinal(2))
    println(ordinal(3))
    println(ordinal(11))
}

위의 내용을 실행하면 아래와 같은 결과가 나온다.

2가 입력 되었을 경우 1, 3, 7, 8, 20에 해당 하지 않기 때문에 else로 오게 되고 numbers에서 가져온 zwei에 te만 붙여서 나온다. 3의 경우에는 바로 해당 되는 내용이 있어서 "dritte"가 출력 된다. 11의 경우도 해당 하는 경우가 없어서 else에서 처리 되며 elf + te가 출력 되게 된다.

when 식의 판단 기준이 될 수 있는 곳에는 set을 사용할 수도 있다.

fun mixColors(first: String, second: String) =
    when (setOf(first, second)) {
        setOf("red", "blue") -> "purple"
        setOf("red", "yellow") -> "orange"
        setOf("blue", "yellow") -> "green"
        else -> "unknown"
    }

fun mixColor() {
    println(mixColors("red", "blue"))
    println(mixColors("blue", "red"))
    println(mixColors("blue", "purple"))
}

다음은 실행 결과이다.

Set의 순서는 중요하지 않다는 것을 알 수 있다.

 

728x90
반응형

'Develop! > Kotlin' 카테고리의 다른 글

구조 분해 선언 in Kotlin  (0) 2023.09.06
Data Class in Kotlin  (0) 2023.09.04
오버로딩(OverLoading) in Kotlin  (0) 2023.08.18
이름 붙은 인자, 가변인자 in kotlin  (0) 2023.08.16
확장함수 in kotlin  (0) 2023.08.14