yohhoyの日記

技術的メモをしていきたい日記

エルビス演算子(Elvis operator)

プログラミング言語Javaに対して、Project Coinで提案されていた エルビス演算子(Elvis operator)?:についてメモ*1。Groovy 1.5では同演算子採用されており、GroovyからJavaへのフィードバック提案となっている。

二項演算子の一種。左オペランドが非nullならば左オペランドの値を、左オペランドがnullならば右オペランドを評価して返す(短絡評価)。機能的にはC#null合体演算子(null-coalescing operator)??や、gccでのGNU C拡張 “条件演算子 ?: で第2項を省略” と等価。

FEATURE SUMMARY:
The ?: binary "Elvis" operator results in the value of the left-hand-side if it is not null, avoiding evaluation of the right-hand-side. If the left-hand-side is null, the right-hand-side is evaluated and is the result.

SIMPLE EXAMPLE:

String s = mayBeNull ?: "null";

whereas, today this is written:

String s = (mayBeNull != null ? mayBeNull : "null");

or (since many developers and coding shops disapprove of the ternary [7]):

String s;
if (mayBeNull != null) {
  s = mayBeNull;
} else {
  s = "null";
}
PROPOSAL: Elvis Operator for Java

メモ:条件演算子(c ? t : f)を避けるコーディング規約や開発者なら、結局はこの演算子も忌避しそうな…

関連URL

*1:いわゆるEmoticon/Smiley的な解釈。wikipedia:en:Elvis_Presley