0
0

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 5 years have passed since last update.

文字列を数値に変換

Last updated at Posted at 2018-11-19

文字列を数値に変換する場合、今までは try ~ catch したり、if("文字列".isNotEmpty() "文字列".toInt() else 0や正規表現で考慮する必要があったが、Kotlin1.1からtoIntOrNull()が追加された
正規表現などでやるよりずっと楽で便利

  "1".toIntOrNull()         // 1
  "hoge".toIntOrNull()      // null
  "hoge".toIntOrNull() ?: 0 // デフォルト値を設定するときとか
  "hoge".toInt()            // NumberFormatExceptionが発生する

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?