技術関係

Kotlin1.4未満ではifの分岐数によってIntellij IDEAが型推論してくれない場合がある

Kotlin1.3で何故かelse ifを使った場合に型推論出来ない場面に遭遇したのでメモ。

スポンサーリンク
スポンサーリンク

環境

Kotlin: 1.3.72

Kotlinの型推論が効かない?

こんな感じの記述を書く。

fun init(mozi: String?) {
    val result = if (mozi == "moge") {
        setOf(1, 2)
    } else if (mozi == null) {
        emptySet()
    } else {
        null
    }
}

しかし、何故かエラーを吐いてうまく型推論してくれない。
emptySet()の所のメッセージを見るとこう。

 

nullの方はこう。

 

when式で書き換えてみる。

すると何故かエラーを吐かず型推論してくれる。

fun init(mozi: String?) {
    val result = when (mozi) {
        "moge" -> {
            setOf(1, 2)
        }
        null -> {
            emptySet()
        }
        else -> {
            null
        }
    }
}

ifの最初の分岐でnullを返してみる。

これもエラーを吐かない。

fun init(mozi: String?) {
    val result = if (mozi == "moge") {
        null
    } else if (mozi == null) {
        emptySet()
    } else {
        setOf(1, 2)
    }
}

どうやら変数に型を明示するか、emptySetで型を明示するしかないらしい。

Kotlin1.4にアップデートしてみる。

kotlin1.4が出たのでbuild.gradleを書き換えて試してみる。

plugins {
    id("org.springframework.boot") version "2.2.4.RELEASE"
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    kotlin("jvm") version "1.4.0"
    kotlin("plugin.spring") version "1.3.61"
}

 

すると・・・型推論出来てる!すごい!

どうやら型推論アルゴリズムが強化されたらしい。

Kotlin 1.4 uses a new, more powerful type inference algorithm. You were already able to try this new algorithm with Kotlin 1.3 by specifying a compiler option, and now it’s used by default. You can find the full list of issues fixed in the new algorithm in YouTrack. In this blogpost, we’ll highlight some of the most noticeable improvements.

調べてみるとkotlin1.4から型推論アルゴリズムが強化されていた。なるほど。
https://kotlinlang.org/docs/whatsnew14.html#new-compiler

コメント

タイトルとURLをコピーしました