One major advantage in Kotlin is its Type System. It eliminates the the danger of having null references.
One major advantage in Kotlin is its Type System. It eliminates the the danger of having null references.
For example, if we declare and initialize a variable, it cannot be set to null anytime after.
var name: String = "John"
name = null
In the above example, name = null will cause a compilation error.
Nullable References
To allow variables to accept null values, we use the "?" symbol after the type.
var nane: String? = "John"
Now we can set the variable to null.
name = null
However, when we try to access a property of a nullable variable, it will not allow us to. We will get a compilation error.
var numberOfCharactersInName = name.length
Handling Nullable References
To safely access a property of a nullable reference, we need to use the Safe Call operator (?).
var numberOfCharactersInName = name?.length
In the example, the Safe Call operator is placed before the Dot Operator to access the length property from the name variable.
Another way we can safely access a property of a nullable reference is to check if the reference is not null using a If Statement.
if(name != null) {
or
var numberOfCharactersInName = if(name != null) name.length else 0
Elvis Operator
The Elvis Operator is similar to an If Statement.
Syntax
[expression] ?: [value_to_return_if_null]
Instead of using the full If statement - if(name != null) ... else ... - we can shorten the code with the Elvis Operator.
var numberOfCharactersInName = name?.length?: 20;
If the expression on the left of the (?:) is not null, it will return that value, otherwise, it will return the value on the right.
Not-Null Assertion Operator (!!)
The Not-Null Assertion Operator (!!) forces the compiler to ignore its checks on the reference to check whether the value is null or not.
var numberOfCharactersInName = name!!.length;
If name = null, it will throw an error.