Bird
0
0

Given a list of Any elements, how can you create a new list containing only the String elements using Kotlin?

hard📝 Application Q8 of 15
Kotlin - Data Types
Given a list of Any elements, how can you create a new list containing only the String elements using Kotlin?
Aval strings = list.filter { it is Any }
Bval strings = list.filterIsInstance<String>()
Cval strings = list.map { it.toString() }
Dval strings = list.filter { it != null }
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering by type

    Kotlin provides filterIsInstance<T>() to filter elements of a specific type.
  2. Step 2: Apply filterIsInstance for String

    Using filterIsInstance() returns a list with only String elements.
  3. Final Answer:

    val strings = list.filterIsInstance<String>() -> Option B
  4. Quick Check:

    filterIsInstance filters by type correctly [OK]
Quick Trick: Use filterIsInstance() to get elements of type T [OK]
Common Mistakes:
MISTAKES
  • Filtering by Any instead of String
  • Mapping toString instead of filtering
  • Filtering only non-null without type check

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes