4. Identify the error in this Kotlin code snippet:
var number: Int? = 10
var result: Int = number + 5
medium
A. Variable 'result' should be nullable.
B. Variable 'number' cannot be nullable.
C. Missing semicolon after declaration.
D. Cannot add Int? and Int directly.
Solution
Step 1: Check type compatibility
number is nullable Int?, but result expects non-null Int. Adding nullable and non-null directly is not allowed.
Step 2: Understand Kotlin's null safety
You must safely unwrap number before adding, e.g., using number ?: 0 or safe call.
Final Answer:
Cannot add Int? and Int directly. -> Option D
Quick Check:
Nullable + non-null Int needs safe unwrap [OK]
Hint: Nullable Int can't be used directly in arithmetic [OK]
Common Mistakes:
Assuming nullable Int can be used like Int
Ignoring need for safe call or Elvis operator
Thinking semicolon is required in Kotlin
5. You have a nullable list of nullable Strings: val items: List?. How do you safely print the length of the first item or print 0 if the list or first item is null?
hard
A. println(items?.get(0)?.length ?: 0)
B. println(items[0].length)
C. println(items!!.get(0)!!.length)
D. println(items?.get(0).length ?: 0)
Solution
Step 1: Analyze nullable types
items can be null, and its elements can be null. So both list and first item need safe calls.
Step 2: Use safe calls and Elvis operator
items?.get(0)?.length ?: 0 safely accesses first item length or returns 0 if null.