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:
?., which returns null if the object itself is null, and calls the method/field otherwise: name?.length.?:, to set a default value if the left side is null: val length = name?.length ?: 0if (name != null) { println(name.length) }
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.
Can you assign
nullto a typeval 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.
Story
In a banking application project, a variable of type
Userstored the result of a client search. The developer definedvar 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.