12.7 Nullable Type
Kotlin nullable types are a concept that does not exist in most other programming languages (with the exception of the optional type in Swift). The purpose of nullable types is to provide a safe and consistent approach to handling situations where a variable may have a null value assigned to it. In other words, the objective is to avoid the common problem of code crashing with the null pointer exception errors that occur when code encounters a null value where one was not expected.
By default, a variable in Kotlin cannot have a null value assigned to it. Consider, for example, the following code:
val username: String = null
An attempt to compile the above code will result in a compilation error similar to the following:
Error: Null cannot be a value of a non-null string type String
If a variable is required to be able to store a null value, it must be specifically declared as a nullable type by placing a question mark (?) after the type declaration...