0
0
Kotlinprogramming~5 mins

Safe call operator (?.) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the safe call operator (?.) do in Kotlin?
It allows you to safely access a property or call a method on an object that might be null, preventing a NullPointerException by returning null instead of crashing.
Click to reveal answer
beginner
How does the safe call operator (?.) behave when the object is null?
When the object is null, the safe call operator returns null immediately without executing the method or property access.
Click to reveal answer
beginner
Example: What is the output of this Kotlin code? val name: String? = null println(name?.length)
The output is 'null' because 'name' is null, so 'name?.length' safely returns null instead of throwing an error.
Click to reveal answer
intermediate
Can the safe call operator (?.) be chained in Kotlin?
Yes, you can chain multiple safe calls like 'obj?.property?.method()' to safely navigate through multiple nullable references.
Click to reveal answer
intermediate
What is the difference between the safe call operator (?.) and the non-null asserted call (!!) in Kotlin?
The safe call operator returns null if the object is null, avoiding exceptions. The non-null asserted call (!!) throws a NullPointerException if the object is null.
Click to reveal answer
What does the safe call operator (?.) return if the object is null?
Anull
BThrows NullPointerException
CEmpty string
DZero
Which Kotlin operator throws an exception if the object is null?
A?.
B?
C!!
D?:
How would you safely access the length of a nullable String 'text'?
Atext.length
Blength?.text
Ctext!!
Dtext?.length
Can you chain safe calls like 'obj?.property?.method()' in Kotlin?
AYes
BNo
COnly for properties
DOnly for methods
What is the output of this code? val user: User? = null println(user?.name ?: "Unknown")
Anull
BUnknown
CThrows exception
DEmpty string
Explain how the safe call operator (?.) helps prevent null pointer exceptions in Kotlin.
Think about what happens when you try to access something on a null object.
You got /4 concepts.
    Describe a situation where chaining safe calls (?.) would be useful.
    Imagine you have an object inside another object, both could be null.
    You got /4 concepts.