Bird
0
0

What is the problem with this Kotlin code?

medium📝 Debug Q6 of 15
Kotlin - Null Safety
What is the problem with this Kotlin code?
var count: Int? = 5
count = null
val total: Int = count + 10
AThere is no problem; code compiles and runs fine
BVariable count cannot be assigned null because it is not nullable
CThe variable total should be declared as nullable Int
DCannot perform arithmetic on a nullable Int without safe call or non-null assertion
Step-by-Step Solution
Solution:
  1. Step 1: Identify variable types

    count is declared as Int?, meaning it can be null.
  2. Step 2: Analyze the expression

    Adding count + 10 is invalid because count might be null, and Kotlin does not allow arithmetic on nullable types without explicit handling.
  3. Step 3: Correct approach

    Use safe call or non-null assertion, e.g., count?.plus(10) or count!! + 10 if sure not null.
  4. Final Answer:

    Cannot perform arithmetic on a nullable Int without safe call or non-null assertion -> Option D
  5. Quick Check:

    Nullable Int requires safe handling before arithmetic [OK]
Quick Trick: Nullable Int needs safe call or !! before arithmetic [OK]
Common Mistakes:
MISTAKES
  • Assuming nullable Int can be used directly in arithmetic
  • Forgetting to check for null before operations
  • Declaring total as nullable instead of handling count

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes