Null Safety Interview Questions
KOTLIN › Language Idioms
How does Kotlin's null safety work? Explain nullable types, the safe call operator, the Elvis operator and the not-null assertion.
What a strong answer covers: Types are non-null by default; String? can hold null and the compiler forces you to handle it. ?. calls only if non-null and otherwise yields null, ?: supplies a fallback (or a throw or return) when the left side is null, and !! asserts non-null and throws NullPointerException if it's wrong. Smart casts let you use a value as non-null after a null check.
Why is !! considered a code smell? What would you replace it with?
What a strong answer covers: !! moves a compile-time guarantee back to a runtime crash and hides the question of why the value might be null. Replacements: ?.let, ?: with a sensible default or early return, requireNotNull or checkNotNull with a message when null really is a programming error, lateinit for injected fields, or reshaping the type so null isn't possible at all.
What are platform types, and how can calling Java code still give you a NullPointerException in Kotlin?
What a strong answer covers: Values coming from Java without nullability annotations are platform types (String!), which Kotlin lets you treat as either nullable or non-null. If you assign one to a non-null type and Java returns null, you crash at that point. The fix is to annotate Java with @Nullable/@NonNull, treat returns as nullable at the boundary, or wrap Java APIs in a Kotlin layer that decides.
When does a smart cast fail even after you've checked for null, and how do you work around it?
What a strong answer covers: Smart casts need the compiler to prove the value can't change between the check and the use. They fail for var properties (another thread or a setter could change them), open or custom-getter properties, and properties from another module. Workarounds: copy into a local val, use ?.let, or make the property a val.
Kotlin is null safe, yet production apps still crash with NullPointerException. Name the ways that happens and how you'd prevent each.
What a strong answer covers: Common sources: !!, platform types from Java and Android SDK calls, uninitialised lateinit (UninitializedPropertyAccessException), reflection-based JSON parsers like Gson setting non-null fields to null by bypassing constructors, leaking 'this' from a constructor so a subclass reads an uninitialised property, and Java interop through generics. Prevention: ban or review !!, annotate boundaries, use a Kotlin-aware serializer (kotlinx.serialization or Moshi codegen), and lint rules.