- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 273字
- 2021-07-02 18:48:34
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.

Source: http://dobsondev.com/2014/06/06/the-elvis-operator/
- 精通Nginx(第2版)
- Drupal 8 Configuration Management
- 小學生C++創意編程(視頻教學版)
- Unity 3D腳本編程:使用C#語言開發跨平臺游戲
- C++編程兵書
- Android Development Tools for Eclipse
- 并行編程方法與優化實踐
- Visual C++開發寶典
- Python Social Media Analytics
- 虛擬現實:引領未來的人機交互革命
- JavaScript高級程序設計(第4版)
- 開源網絡地圖可視化:基于Leaflet的在線地圖開發
- Unity與C++網絡游戲開發實戰:基于VR、AI與分布式架構
- Instant SQL Server Analysis Services 2012 Cube Security
- Python編程基礎