Recall & Review
beginner
What does the Elvis operator (?:) do in Kotlin?
The Elvis operator returns the value on its left if it is not null; otherwise, it returns the value on its right. It helps provide default values when dealing with nullable variables.
Click to reveal answer
beginner
How do you use the Elvis operator to assign a default value to a nullable variable?
You write:
val result = nullableValue ?: defaultValue. If nullableValue is null, result gets defaultValue.Click to reveal answer
beginner
Example: What is the output of
val name: String? = null; println(name ?: "Guest")?The output is
Guest because name is null, so the Elvis operator returns the default string "Guest".Click to reveal answer
intermediate
Can the Elvis operator be chained in Kotlin?
Yes, you can chain Elvis operators like
val result = a ?: b ?: c. It returns the first non-null value from left to right.Click to reveal answer
beginner
Why is the Elvis operator useful in real-life Kotlin programming?
It simplifies code by avoiding explicit null checks and providing easy default values, making programs safer and cleaner.
Click to reveal answer
What does the Elvis operator (?:) return if the left side is not null?
✗ Incorrect
The Elvis operator returns the left side value if it is not null.
Which Kotlin code uses the Elvis operator correctly to provide a default value?
✗ Incorrect
The Elvis operator syntax is
?:, so nullable ?: default is correct.What will
val age: Int? = null; val result = age ?: 18 assign to result?✗ Incorrect
Since
age is null, the Elvis operator returns the default value 18.Can the Elvis operator be used with non-nullable types?
✗ Incorrect
Yes, the Elvis operator can be used with non-nullable types on the left side (though redundant since the right side is never used), in addition to nullable types.
What is the main benefit of using the Elvis operator in Kotlin?
✗ Incorrect
The Elvis operator helps shorten code by providing default values without explicit null checks.
Explain how the Elvis operator (?:) works in Kotlin and give a simple example.
Think about how to provide a fallback value when something might be null.
You got /3 concepts.
Describe a real-life situation where using the Elvis operator can make your Kotlin code cleaner and safer.
Imagine you ask for a user's name but they might not enter it.
You got /3 concepts.