Kotlin - Null SafetyFind the issue in this Kotlin code: val list: MutableList = mutableListOf("a", "b") list.add(null) list.forEach { println(it.length) }ACalling length on a nullable String without safe call causes a runtime exception.BCannot add null to MutableList<String?>.CMutableList cannot be iterated with forEach.DNo issues; code runs fine.Check Answer
Step-by-Step SolutionSolution:Step 1: Understand list type and null additionThe list allows nulls because element type is String?. Adding null is valid.Step 2: Analyze forEach usageInside forEach, it.length is called without safe call operator. Since it can be null, this causes a runtime NullPointerException.Final Answer:Calling length on a nullable String without safe call causes a runtime exception. -> Option AQuick Check:Nullable elements require safe calls to avoid exceptions [OK]Quick Trick: Use ?.length for nullable strings to avoid exceptions [OK]Common Mistakes:MISTAKESAssuming adding null is invalidThinking forEach cannot iterate MutableListIgnoring null safety when accessing properties
Master "Null Safety" in Kotlin9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Kotlin Quizzes Collections Fundamentals - Collection size and emptiness checks - Quiz 14medium Collections Fundamentals - Mutable vs immutable interfaces - Quiz 1easy Control Flow as Expressions - When as expression returning value - Quiz 15hard Data Types - Number literal formats (underscore, hex, binary) - Quiz 14medium Functions - Single-expression functions - Quiz 6medium Functions - Named arguments for clarity - Quiz 1easy Kotlin Basics and JVM Runtime - What is Kotlin - Quiz 15hard Loops and Ranges - Repeat function for simple repetition - Quiz 3easy Loops and Ranges - While and do-while loops - Quiz 8hard Operators and Expressions - Operator precedence - Quiz 4medium