Kotlin Null Safety
Kotlin is a statically typed programming language developed by JetBrains. One of the key features that make Kotlin stand out is its built-in null safety feature. Null safety is the concept of eliminating the risk of null references, which are often the common cause of the Null Pointer Exceptions (NPE), the so-called "Billion Dollar Mistake". This tutorial will introduce you to Kotlin's null safety and how it helps to prevent the dreaded NullPointerException
.
Nullable Types and Non-Nullable Types
In Kotlin, types of objects are non-nullable by default. If you try to assign or return null in your code, the compiler will throw an error.
var name: String = "John Doe"
name = null // Compilation error
However, Kotlin provides a way to declare a nullable type. By adding a question mark ?
after the type, you're telling the compiler that the variable can hold a null reference.
var name: String? = "John Doe"
name = null // This is OK
Safe Calls
Kotlin provides a safe call operator ?.
to safely access a method or property of a possibly null object. If the object is null, the expression will return null.
val length: Int? = name?.length
In the above example, if name
is not null, it will return the length of the string, otherwise, it will return null.
Elvis Operator
The Elvis operator ?:
in Kotlin is used to return the not null value even the conditional expression is null. It is used to avoid null pointer exception in the code.
val len = name?.length ?: 0
In this example, if name
is not null, len
will hold the length of name
string. But if name
is null, then len
will hold the value 0
.
Non-Null Assertion Operator
Sometimes, you might be sure that a nullable reference is definitely not null. In this case, you can use the non-null assertion operator !!
. This will convert a nullable reference to a non-nullable one, and throw an exception if the reference is null.
val len = name!!.length
In the above example, if name
is not null, len
will hold the length of name
string. But if name
is null, a KotlinNullPointerException
will be thrown.
Safe Casts
Kotlin provides the as?
operator for safe casts. If the casting is not possible, instead of throwing a ClassCastException
, it returns null.
val obj: Any = "String"
val str: String? = obj as? String
Conclusion
That's a basic overview of null safety in Kotlin. Null safety is one of the best features in Kotlin and it helps to eliminate the risk of null references in the code. Always remember to use nullable types and safe calls whenever needed to avoid unexpected crashes in your application. Keep practicing and you will get more comfortable with these concepts. Happy coding!