Safe Call Operator
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 14 of 93.
When you have a nullable variable, you can't directly call methods or access properties on it: the compiler won't allow it because the value might be null. The safe call operator ?. solves this problem elegantly.
Instead of using a regular dot ., you use ?. to safely access members of a nullable type:
fun main() {
val name: String? = "Alice"
val length = name?.length // Returns 5
println(length)
val nullName: String? = null
val nullLength = nullName?.length // Returns null (no crash!)
println(nullLength)
}The safe call operator checks if the value is null before accessing the property or method. If the value is null, the entire expression returns null instead of crashing. If the value exists, it works just like a normal call.
You can also chain multiple safe calls together:
fun main() {
val text: String? = "Hello"
val result = text?.uppercase()?.length
println(result) // Prints: 5
}If any part of the chain is null, the entire expression safely returns null without throwing an error.
Challenge
EasyYou are provided with the following nullable variable:
val message: String? = "Kotlin"Use the safe call operator to:
- Get the length of
messageand print it - Convert
messageto uppercase and print the result
Then, create another nullable variable:
val empty: String? = nullUse the safe call operator to get the length of empty and print it.
Each result should be printed on a separate line. Remember: the safe call operator returns
nullwhen the value isnull.
Try it yourself
fun main() {
val message: String? = "Kotlin"
// TODO: Use the safe call operator to get the length of message and print it
// TODO: Use the safe call operator to convert message to uppercase and print it
val empty: String? = null
// TODO: Use the safe call operator to get the length of empty and print it
}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