Elvis Operator
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 15 of 93.
The safe call operator is great for avoiding crashes, but sometimes you need an actual value instead of null. The Elvis operator ?: lets you provide a default value when an expression is null.
The syntax is simple: place ?: after a nullable expression, followed by the fallback value:
fun main() {
val name: String? = null
val displayName = name ?: "Guest"
println(displayName) // Prints: Guest
}If the left side is not null, that value is used. If it's null, the right side becomes the result. This works perfectly with safe calls:
fun main() {
val text: String? = null
val length = text?.length ?: 0
println(length) // Prints: 0
val greeting: String? = "Hello"
val greetingLength = greeting?.length ?: 0
println(greetingLength) // Prints: 5
}The operator gets its name because ?: looks like Elvis's hair when viewed sideways. More importantly, it gives you a clean way to convert nullable types into non-nullable values with sensible defaults.
Challenge
EasyA parcel has an optional tracking label and an optional destination. The starter provides both nullable values. Use ?: to choose "Pending" when the tracking label is missing and "Unassigned" when the destination is missing. Print the chosen label, then the chosen destination, on separate lines.
Try it yourself
fun main() {
val trackingLabel: String? = null
val destination: String? = "Harbor"
// Choose and print the two display values.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground