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 エルビス演算子(?:)の使い方

Last updated at Posted at 2021-10-11

Kotlinでエルビス演算子を使うことがあったのでメモがてらここに残しておきます。

エルビス演算子とは?

Kotlinはnullが嫌いな言語です、しかしときにはnullを扱う必要があります。
以下のコードのようにif分などでnullじゃない場合は〜などの条件分岐もかけますが、エルビス演算子ならもっとスマートにかけます

//if分のnullの場合の条件分岐

val hoge = if(test != null) "hoge" else "nullだよ"

エルビス演算子の場合

val test = "hoge" ?: "nullだよ"
1
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
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?