Kotlin - Null SafetyGiven a list of nullable Strings, how do you create a list of their lengths, ignoring nulls safely?Aval lengths = list.map { it.length }Bval lengths = list.mapNotNull { it?.length }Cval lengths = list.filter { it != null }.map { it.length }Dval lengths = list.map { it?.length ?: 0 }Check Answer
Step-by-Step SolutionSolution:Step 1: Understand list of nullable StringsElements can be null, so safe handling is needed.Step 2: Use mapNotNull with safe callmapNotNull applies function and removes null results safely.Final Answer:val lengths = list.mapNotNull { it?.length } -> Option BQuick Check:mapNotNull + safe call = filtered non-null lengths [OK]Quick Trick: Use mapNotNull with '?.' to skip nulls safely [OK]Common Mistakes:MISTAKESUsing map without null filteringAssuming filterNotNull then map is simplerReplacing null lengths with zero instead of skipping
Master "Null Safety" in Kotlin9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Kotlin Quizzes Collections Fundamentals - Mutable vs immutable interfaces - Quiz 3easy Collections Fundamentals - Array creation and usage - Quiz 2easy Functions - Local functions (nested functions) - Quiz 3easy Functions - Vararg parameters - Quiz 9hard Kotlin Basics and JVM Runtime - Print and println output - Quiz 13medium Kotlin Basics and JVM Runtime - Main function as entry point - Quiz 5medium Null Safety - Safe casts with as? - Quiz 10hard Null Safety - Null safety in collections - Quiz 4medium Null Safety - Nullable types with ? suffix - Quiz 5medium Variables and Type System - String templates and interpolation - Quiz 7medium