1
2

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.

【Kotlin】null の場合にデフォルト値を返す

Last updated at Posted at 2019-08-03

nullable な型の値が null だった場合にデフォルト値を返す、
というような拡張関数は標準ライブラリーにはないようでした。

ではどうするか。

単純な場合
getValueOrNull() ?: getDefaultValue()
△チェインする場合
(getValueOrNull() ?: getDefaultValue())
    .let { ... }
○チェインする場合
getValueOrNull().let { it ?: getDefaultValue() }
    .let { ... }
拡張関数を自作する場合
inline fun <T> T?.onNull(block: () -> T): T = this ?: block()

getValueOrNull().onNull { getDefaultValue() }

/以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?