Bird
0
0

How can you safely call a method process() on an object obj that might be null, and if null, call defaultProcess() instead?

hard📝 Application Q9 of 15
Kotlin - Null Safety
How can you safely call a method process() on an object obj that might be null, and if null, call defaultProcess() instead?
Aobj.process() ?: obj.defaultProcess()
Bobj.process() ?: defaultProcess()
Cobj?.process() && defaultProcess()
Dobj?.process() ?: defaultProcess()
Step-by-Step Solution
Solution:
  1. Step 1: Use safe call to call process() if obj not null

    The safe call obj?.process() calls process() only if obj is not null.
  2. Step 2: Use Elvis operator to call defaultProcess() if obj is null

    The Elvis operator ?: calls defaultProcess() if the safe call returns null.
  3. Final Answer:

    obj?.process() ?: defaultProcess() -> Option D
  4. Quick Check:

    Safe call + Elvis operator for fallback method call [OK]
Quick Trick: Use ?. with ?: to provide fallback method call [OK]
Common Mistakes:
MISTAKES
  • Calling method without safe call on nullable
  • Using logical operators instead of Elvis
  • Calling methods on null without checks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes