Kotlin Code Pills — Null Safe
One of the most common problem in many programming languages, like Java, is that while accessing an object of a null reference will result in a null reference exception. Kotlin aimed to solve this common NullReferenceException
. Kotlin uses type inference.
In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).
For example, a regular variable of type String
can not hold null
var a: String = "hello, world!"
a = null // compilation error
To allow nulls, we can declare a variable as a nullable string, written String?
:
var b: String? = "hello, world!"
b = null // ok
print(b)
This makes the code more concise and gives more control while coding.
See you next coding pill.