LoginSignup
1
0

More than 3 years have passed since last update.

?: < I'm Elvis演算子

Posted at

Elvis演算子とは

?:

Kotlinで変数がnullの場合に代替物を使いたい時に使う。

使い方

https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator から引用

val l: Int = if (b != null) b.length else -1

↑みたいなnullチェックをしなくても

val l = b?.length ?: -1

で書けて便利。

?: SomeException()みたいにデータ取得時の例外出力時に使ったりします。

Why Elvis演算子?

公式にはしれっとElvis演算子とだけ書かれていてなぜそんな命名なのかは名言ないですが、
右に90度回転させるとエルヴィス・プレスリーのようなリーゼント頭に見えるから、だと思われます。
強烈な印象は学習を促進させるので良いですね。

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