0
0
Kotlinprogramming~5 mins

Elvis operator (?:) for default values in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe right side value
BAn error
CNull
DThe left side value
Which Kotlin code uses the Elvis operator correctly to provide a default value?
Aval x = nullable ?: default
Bval x = nullable ? default
Cval x = nullable || default
Dval x = nullable && default
What will val age: Int? = null; val result = age ?: 18 assign to result?
A0
Bnull
C18
DError
Can the Elvis operator be used with non-nullable types?
ANo, only with nullable types
BYes, always
COnly with strings
DOnly with numbers
What is the main benefit of using the Elvis operator in Kotlin?
ATo shorten code by avoiding explicit null checks
BTo create loops
CTo declare variables
DTo handle exceptions
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.