官术网_书友最值得收藏!

Elvis operator

The elvis operator is represented by a question mark followed by a colon (?:) and has a syntax such as the following:

    first operand ?: second operand 

The elvis operator works as follows: if first operand is not null, then this operand will be returned, otherwise second operand will be returned. The elvis operator allows us to write very concise code.

We can apply the elvis operator to our example to retrieve the variable locked, which will always be non-nullable:

override fun onCreate(savedInstanceState: Bundle?) { 
super.onCreate(savedInstanceState) 
val locked: Boolean = savedInstanceState?.getBoolean("locked") ?: false 
} 

In the preceding example, the elvis operator will return a value of the savedInstanceState?.getBoolean("locked") expression if savedInstanceState is not null, otherwise it will return false. This way we can make sure that the locked variable will always have a non-nullable value. Thanks to the elvis operator, we can define a default value. Also, note that the right-hand side expression is evaluated only if the left-hand side is null. It is then providing a default value that will be used when the expression is nullable. Getting back to our quiz example from the previous section, we can easily modify the code to always return a non-nullable value:

    val correct = quiz.currentQuestion?.answer?.correct ?: false 

As the result, the expression will return the value returned by the correct property or false if any object in the safe call chain is null. This means that the value will always be returned, so non-nullable Boolean type is inferred.

The operator name comes from the famous American singer-songwriter Elvis Presley, because his hairstyle is similar to a question mark:

Source: http://dobsondev.com/2014/06/06/the-elvis-operator/

主站蜘蛛池模板: 陆河县| 金阳县| 巴楚县| 定结县| 封丘县| 河北区| 柘城县| 永登县| 浙江省| 永登县| 普兰县| 固阳县| 桓台县| 饶平县| 文登市| 毕节市| 健康| 通化市| 阿巴嘎旗| 磴口县| 准格尔旗| 奉化市| 丰镇市| 北宁市| 卓尼县| 垦利县| 冀州市| 永清县| 石棉县| 海阳市| 吉隆县| 肥西县| 泰宁县| 广西| 西吉县| 进贤县| 井陉县| 安岳县| 朝阳区| 罗定市| 永安市|