- In Kotlin, there are several ways to handle nullability and avoid null pointer exceptions. Let's look at some of them:
Safe Call Operator (?.):
- If the object is null, the expression will return null instead of throwing a null pointer exception.
val str: String? = null
val length: Int? = str?.length // prints null
Safe Call with let (?.let):
- Executes the block only if the value is not null
val str: String? = "hello"
str?.let {
println(it.length)
}
Elvis Operator (?:):
- It is used to provide a default value if an expression is null. similar to using if else.
val length = name?.length ?: -1
//is similar to
val length = if(name != null) name.length
else -1
Not-Null Assertion Operator (!!):
- If the expression is null, a null pointer exception will be thrown at runtime.
- Use the not-null assertion operator
!! when you are sure that an expression is not null, and you want to force the compiler to treat it as such.
val str: String? = null
val length: Int = str!!.length // Exception is thrown