0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Android+Kotlin null安全が崩れるパターン

Posted at

v1がnullの場合、Integer.parseInt(null)になる。

var v1: String? = getVal()
val v2 = v1.let { // [1]
    Integer.parseInt(it) // [2]itはnon nullであって欲しい
} ?: run{
    return // ここには決して処理は来ない
}

java側の定義が↓こうで、引数のStringにアノテーションが無いからだと思う。

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
}

kotlinとしては完全に正しい、Integer.parseIntの引数はアノテーションがないからnullの可能性もある だから[2]のitはString?で問題ない。というロジックだろう。

letの前に?を付けてもコンパイルは成立する。
nullableかどうかはkotlinの最重要ポイントなのに、?が有っても無くてもどっちでも意味が通るのが違和感ある。
個人的には、こういう場合は以下のコードに強制して欲しいけどそういうlintあるかな

var v1: String? = getVal()
val v2 = v1?.let {
    Integer.parseInt(it)
} ?: run{
    return // 今回、こっちは実行される可能性ある
}

というお話でした

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?