Bird
0
0

What will be the output of the following Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Null Safety
What will be the output of the following Kotlin code?
val list: List = listOf("apple", null, "banana")
val filtered = list.filterNotNull()
println(filtered)
A["apple", null, "banana"]
B[null]
C["apple", "banana"]
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand filterNotNull() behavior

    This function removes all null elements from a collection, returning a list of non-null elements.
  2. Step 2: Apply filterNotNull() on the list

    Original list has "apple", null, "banana". After filtering, only "apple" and "banana" remain.
  3. Final Answer:

    ["apple", "banana"] -> Option C
  4. Quick Check:

    filterNotNull() removes nulls [OK]
Quick Trick: filterNotNull() removes all nulls from collections [OK]
Common Mistakes:
MISTAKES
  • Expecting nulls to remain after filterNotNull()
  • Thinking filterNotNull() causes compile error
  • Confusing filterNotNull() with filter()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes