LoginSignup
4
2

More than 5 years have passed since last update.

Kotlinでnull+nullするとNonNullになる

Posted at

ある時、null + nullするとNonNullになったので少し調べました。

val hoge: String = null // エラー
val hoge: String = null + null // エラーじゃない

+を参照すると次のようになっていました。

public operator fun String?.plus(other: Any?): String

次のような場面で遭遇しました。
MapgetはNullableなので、強制アンラップしたり、例外にしたりでしたが、conf2のようなパターンでは突然NonNullになっています。nullnullにいつの間にかならないように注意しないと行けなさそうです。なんか不思議な感じ。

val config = mapOf("aaa" to "bbb")
val conf1: String = config["hoge"] ?: throw Exception() // -> throw Exception
val conf2: String = config["hoge"] + config["fuga"] // -> conf2 = nullnull
4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2