Null Safety Flashcards

KOTLIN › Language Idioms

What is the difference between String and String? in Kotlin?
String is a non-null type that can never hold null; assigning null is a compile error. String? is a nullable type that may hold null, so the compiler forces you to handle the null case before dereferencing.
What does the safe call operator ?. do, and what type does it return?
It evaluates the call only if the receiver is non-null; if the receiver is null it short-circuits to null instead of throwing. The result type is nullable (e.g. a?.length returns Int?).
What does the elvis operator ?: do, and is its right side always evaluated?
a ?: b returns a if it is non-null, otherwise b. The right side is only evaluated when the left is null (short-circuit), so it is a safe place for defaults, return, or throw.
What does !! do and when should you avoid it?
!! asserts a value is non-null, converting T? to T, and throws NullPointerException if it is actually null. Avoid it except when you can prove the value cannot be null; it defeats the purpose of null safety.
What is the difference between as and as? when casting?
as is an unsafe cast that throws ClassCastException on failure. as? is a safe cast that returns null on failure, so its result type is nullable and is typically paired with elvis (x as? Type ?: default).
What is a smart cast and when does the compiler refuse to apply one?
After a null or type check the compiler automatically treats the value as the narrower non-null type within that scope. It is refused when the value could change between the check and use, such as a mutable var or a custom-getter property.
What is a platform type (Type!) and why is it dangerous?
It is a type from unannotated Java with unknown nullability, written T!. The compiler relaxes null checks, so you can call it without ?., but it throws NPE at runtime if the Java value was actually null.
How do you run a block only when a nullable value is non-null using let?
Use value?.let { ... }. The safe call skips the block when value is null; inside the block it is bound to the non-null it (or a named param), giving a clean scoped non-null path.
How do you turn a List<String?> into a List<String> with the nulls removed?
Call filterNotNull(), which removes all null elements and returns a List with the non-null element type. (mapNotNull does the same while also transforming.)

Back to Null Safety