Bird
0
0

Which of the following Kotlin expressions correctly uses the Elvis operator to assign a default value of 10 when num is null?

easy📝 Conceptual Q2 of 15
Kotlin - Null Safety
Which of the following Kotlin expressions correctly uses the Elvis operator to assign a default value of 10 when num is null?
Aval result = num ?: 10
Bval result = num ? 10
Cval result = num ?: "10"
Dval result = num ??: 10
Step-by-Step Solution
Solution:
  1. Step 1: Review correct Elvis operator syntax

    The Elvis operator is ?: and is used as variable ?: defaultValue.
  2. Step 2: Check each option

    val result = num ?: 10 uses ?: correctly with a numeric default. val result = num ? 10 uses a single question mark which is invalid. val result = num ?: "10" uses a string default which is a type mismatch if num is numeric. val result = num ??: 10 uses ??: which is invalid syntax.
  3. Final Answer:

    val result = num ?: 10 -> Option A
  4. Quick Check:

    Correct Elvis syntax = val result = num ?: 10 [OK]
Quick Trick: Use ?: with correct syntax and matching types [OK]
Common Mistakes:
MISTAKES
  • Using single ? instead of ?:
  • Mismatching default value type
  • Typing ?? or other invalid operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes