LoginSignup
9
3

More than 1 year has passed since last update.

Kotlinのnullチェックはif elseでやるな

Last updated at Posted at 2022-12-27

Kotlinでnullチェックし、nullではない場合とnullの場合でif/elseを使うのは個人的にダサいと思うので共有。
やる場合はlet/?:runを使うべし!

これはダサい例


if (userIcon != null) {
    // userIconが存在 → ユーザー画像を設定
    Image(
        painter = painterResource(id = userIcon),
        contentDescription = null,
    )
} else {
    // userIconがnull → デフォルト画像を設定
    Image(
        painter = painterResource(id = R.drawable.default_image),
        contentDescription = null,
    )
}

if/elseの場合はuserIconがある場合に、再度userIconを渡している。。
Kotlin風のモダンな書き方


userIcon?.let {
    // userIconが存在 → ユーザー画像を設定
    Image(
        painter = painterResource(id = it),
        contentDescription = null,
    )
} ?: run {
    // userIconがnull → デフォルト画像を設定
    Image(
        painter = painterResource(id = R.drawable.default_image),
        contentDescription = null,
    )
}

nullではない場合に、let以降でitでuserIconを取れる。
Kotlin風な書き方でかけて良くなった!!

参考記事
https://ticktakclock.hatenablog.com/entry/2020/02/22/203408

9
3
2

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
9
3