以下の内容はhttps://uga-box.hatenablog.com/entry/2024/07/25/000000より取得しました。


【Kotlin】when式ついて

Kotlinを触ってみていて、when式というの調べてみた

kotlinlang.org

基本的な書き方

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

分岐条件が満たされるまで、引数をすべての分岐と順番に照らし合わせる

条件には型チェックも行えるので、Javaのswitch ~ case文よりも使いやすい

式としても使える

式としても使えるので、条件に一致する分岐の値が変数に格納される

値が取りうる条件分岐を網羅しているとコンパイラが判断できない限り、elseは必須

例えば、以下のような enumを用いた条件分岐の場合、網羅できていると言えるので elseは不要

enum class Bit {
    ZERO, ONE
}

val numericValue = when (getRandomBit()) {
    Bit.ZERO -> 0
    Bit.ONE -> 1
    // 'else' is not required because all cases are covered
}

その他

カンマで繋げれば、複数条件で共通処理を書くことができる

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

条件に関数を用いることができる

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

in!inによる範囲条件使える

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

is!isによる型チェック

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

whenのsubject(when文の括弧内)には変数定義もでき、分岐の中でそれを使うことができる

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

これは、Railway Oriented Programming で使えそう




以上の内容はhttps://uga-box.hatenablog.com/entry/2024/07/25/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14