Kotlin - Null Safety
Given a list of Any objects, how can you safely cast all elements to String and collect only the successful casts?
val items: List= listOf("a", 1, "b", 2) // Fill in the blank val strings = items.mapNotNull { it ___ }
Given a list of Any objects, how can you safely cast all elements to String and collect only the successful casts?
val items: List= listOf("a", 1, "b", 2) // Fill in the blank val strings = items.mapNotNull { it ___ }
as? returns nullable String or null if cast fails.mapNotNull collects only non-null results, so only successful casts remain.15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions