August 2017
Intermediate to advanced
440 pages
10h
English
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") ...
Read now
Unlock full access