ProgrammingKotlin Developer

Explain the features of working with Nullable types in Kotlin. What language tools allow safe handling of null values? Provide a code example and describe best practices.

Pass interviews with Hintsage AI assistant

Answer.

Kotlin implements safe handling of null through its type system: any type cannot be null by default, for example, val a: String = null will cause a compilation error. To indicate the possibility of assigning null, the question mark ? is used, for example:

val name: String? = null

To work with Nullable types, the following are provided:

  • Safe-call operator: ?., which returns null if the object itself is null, and calls the method/field otherwise: name?.length.
  • Elvis operator: ?:, to set a default value if the left side is null: val length = name?.length ?: 0
  • if/when check: Example:
if (name != null) { println(name.length) }
  • Assert operator ( !! ): To forcefully get the value, throwing a NullPointerException if the object is null (used very cautiously):
val length = name!!.length

Best practices: minimize Nullable types, use Safe-call and Elvis operators, avoid !!, and explicitly model situations where null is acceptable.

Trick question.

Can you assign null to a type val a: String, and how to avoid this?

Answer: No, by default in Kotlin types cannot be equal to null. To allow null assignment, you must explicitly specify val a: String? = null. Types without ? are always non-null.

Examples of real errors due to ignorance of the nuances of the topic.


Story

In a banking application project, a variable of type User stored the result of a client search. The developer defined var user: User, but sometimes the client was not found and the service returned null. This caused NPE and massive crashes.


Story

In a support chatbot, !! was used to access user messages (message!!.text), believing that messages always arrive. The bot crashed on the first empty message. Safe-call would have prevented the problem.


Story

In a mobile application, data from the database could not be loaded and came as null. Instead of safe access, the developer used direct access, which led to crashes in all cases of incomplete data.