Null safety

Generally, when we write code, we declare the fields in a class. We are not sure whether or not the field is initialized during execution. To find out, we use null checks and annotations such as @Nullable or @NotNull. Kotlin provides elegant syntax for declaring fields with nullable and non-nullable types, which prevents the problem of accidental NullPointerExceptions (NPEs). Kotlin catches possible null pointers when the code is being compiled, meaning that no null pointer issues will occur after the application has been deployed. This means that there are almost no cases of NullPointerException.

Consider the following code:

object NullabilityTest {
    @JvmStatic
    fun main(args: Array<String>) {
        var msg: String = null
        println(msg)
    }
}

Let's compile the preceding code:

[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.2.41:compile (compile) on project myJavaApp: Compilation failure
[ERROR] ..Intermixing Java and KotlinmyJavaAppsrcmainjavaNullabilityTest.kt:[10,28] Null cannot be a value of a non-null type String

This code gives a compilation error. If we want to assign a null value to a variable, it has to be declared as follows:

var msg: String ?= null

The msg variable can be declared with a null value. Let's consider another example:

object NullabilityTest {
    @JvmStatic
    fun main(args: Array<String>) {
        var userList:ArrayList<String> ?= null
println(userList.get(0)) } }

Variables can be declared to hold a null value. If we invoke any function on these variables, such as userList.get(0)it doesn't throw NullPointerException at runtime. Instead, it just fails to compile:

Error:(6, 25) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.collections.ArrayList<String>? /* = java.util.ArrayList<String>? */

Kotlin catches possible null pointers during compile time. It warns us that we should initialize the var before accessing it. The language provides clear constructs to define which variables can hold a null value, and which can hold a non-null value. When a variable is null, the language provides a safer way to deal with it, avoiding null pointer issues at runtime. This means that there are almost no cases of NullPointerException.

Since the variables have been declared to hold a null value, we need to perform a null check before accessing any function on this variable. Kotlin provides an elegant syntax for null check (?.), as follows:

userList?.get(0)

Kotlin provides an elegant syntax to perform an operation on the variable that can hold null values safely. Consider the following code:

fun main(args: Array<String>) {
    var userList:ArrayList<String> ?= null
var user = userList?.get(0) user ?.let { println("got the user details") } ?: run { println("there is no user") } }

Here, we create a list of users, userList, and try to get the first object and do something with it. In this case, the user instance is null, so when we use ?. on it, it doesn't throw NullPointerException. If the  user instance is not null, it prints a got the user details message to the console. If it is null, it prints a there is no user message.

In short, Kotlin is a feature-packed language, with its simple and concise language constructs. If we already have an application written in Java, we can include Kotlin to get the benefits that it offers. Once the code is compiled, everything is bytecode and no distinction is made between Java or Kotlin. This is possible because Kotlin is interoperable with Java and provides an elegant way of writing code that reduces the development life cycle and is less error prone.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset