Bird
0
0

How can you safely call a function printLength that prints the length of a nullable String text without causing a NullPointerException?

hard📝 Application Q15 of 15
Kotlin - Null Safety
How can you safely call a function printLength that prints the length of a nullable String text without causing a NullPointerException?
Afun printLength(text: String) { println(text.length) } printLength(null)
Bfun printLength(text: String?) { println(text.length) } printLength(null)
Cfun printLength(text: String?) { println(text?.length ?: 0) } printLength(null)
Dfun printLength(text: String) { println(text?.length) } printLength(null)
Step-by-Step Solution
Solution:
  1. Step 1: Understand function parameter nullability

    To accept null, parameter must be String?. Options A and D use non-nullable String, so passing null causes error.
  2. Step 2: Use safe call and default value

    fun printLength(text: String?) { println(text?.length ?: 0) } printLength(null) uses safe call ?. and Elvis operator ?: to print 0 if text is null, avoiding exceptions.
  3. Final Answer:

    fun printLength(text: String?) { println(text?.length ?: 0) } printLength(null) -> Option C
  4. Quick Check:

    Safe call + Elvis handles null safely [OK]
Quick Trick: Use ?. and ?: to safely handle nullable parameters [OK]
Common Mistakes:
MISTAKES
  • Passing null to non-nullable parameter
  • Accessing length without safe call
  • Ignoring default value for null case

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes