Kotlin null Value and Nullable Type Tutorial

In this section, we will learn what the nullable type is and how to use it in Kotlin.

What is null value in Kotlin?

If you have a variable in Kotlin that is currently pointing to an object in the memory and want to cut that reference, we can use the null value.

Basically, when the null value is assigned to a variable, it means the variable exists in the program but currently it points to nothing or simply it has no reference.

Note that if a variable point to an object but then we reassign it to a null value, the target object will stay in the heap memory as long as there are other variables point to it (if any). But the moment that target object lost all the references to itself, there’s a program called Garbage Collector (GC for short) that will come and remove that object entirely from the memory.

What is nullable type variable in Kotlin?

A variable that is capable of holding a null value is called a nullable type.

By default, a variable is not capable of holding null values! If you do so, you’ll get an error, actually!

For example, if you have a variable of type String, you can only store string values in it and nothing else!

So if you want to have a nullable type variable, there’s one more step that you need to do as we shall see now.

How to create a nullable type in Kotlin?

This is how we can create a nullable type variable:

var variableName:data-type? = value

Here, the only difference is the question mark that appeared after the data-type. Simply by adding the question mark after the data-type of variable, that becomes a nullable type variable.

This means the value of the variable can now be either the null value or a value of the specified data-type.

Example: creating a nullable type in Kotlin

fun main(){
    var firstName:String? = null 
    var salary:Int? = 200000
    if (firstName == null){
        println("The value of the firstName variable is null at this time")
    }else{
        println("This is the value of the firstName variable $firstName")
    }
    println(salary)
}

Output:

The value of the firstName variable is null at this time

200000

Here you can see that the firstName and salary variables are of type nullable and that means they can have either the null value or a value of their specified types.

Kotlin Function Parameters of Nullable Type

A nullable variable can appear as the data type of parameters for functions as well.

Simply add a question mark to the data type of the target parameter and that becomes a nullable type parameter!

Note: even if a parameter is of type nullable, you still need to pass an argument for that parameter (doesn’t matter if the argument is null or a non-null value) unless the parameter already has a default value.

Example: creating function parameters of nullable type

fun main(){
    var firstName:String? = null 
    var anotherName:String = "John"
    printName(firstName)
    printName(anotherName)
}

fun printName(name:String?){
    println("The name is: $name")
}

Output:

The name is: null

The name is: John

Kotlin Function Nullable Return Type

Any type in Kotlin can become a nullable as well. This includes the return type of a function!

Just like the way we’ve turned the data type of parameters and variables into nullable, we can turn the data type of the return type of a function into nullabe by adding the question mark at the end of that type.

Example: creating functions with nullable return type in Kotlin

fun main(){
    var res:Int? = multiply(10,20)
    println("The result is: $res")
}

fun multiply(num1:Int?, num2:Int?):Int?{
    if (num1 !=null && num2 !=null){
        return num1 * num2
    }else{
        return null
    }
}

Output:

200

Here the return type of the multiply function is of type nullable Int. This means the function may return either a null value or a value of type Int.

Now look that the data type of the variable we’re trying to assign the result of this function into;

Here, the data type is also a nullable Int! Basically, the data type must be of nullable type! Because there’s no guarantee that the function will always return an Integer value! So if we set the data type of this variable to Int (which is a non-nullable type) we will get an error.

Note: if we don’t set the type of this variable explicitly, the compiler will implicitly turn that into a nullable Int type for us.

Kotlin Nullable Arrays

An array can also be of nullable type!

When creating such type of array, you have this option to either implicitly or explicitly set the type.

For implicitly setting the type, all you need to do is to add a null value as one of the elements of the target array.

But for explicitly setting the data type, this is what we need to do:

var variableName: Array<data-type?> = arrayOf(elements…)

As you can see, the data type of the variable Array<data-type?> has a question mark added to the data-type we’ve set in the pair of <> symbol.

Note: in the Kotlin generic section, we will talk more about the <> symbol.

Example: creating nullable arrays in Kotlin

fun main(){
    var names: Array<String?> = arrayOf("Jack","Ellen", "Omid","Monica",null)
    var colors = arrayOf("Red","Black","Blue",null, null ,null)

    for (element in names){
        println(element)
    }
    println("\n****************")
    for (element in colors){
        println(element)
    }
}

Output:

Jack

Ellen

Omid

Monica

null

****************

Red

Black

Blue

null

null

null

How to Access a Nullable Type in Kotlin?

One of the important aspect of working with nullable type values is how to access them!

To begin with, one of the methods is to use the if statement!

Basically, we check the value of a nullable type variable against the value null (as part of the condition of an if statement) and if the target variable didn’t have a null value, then we go for getting the value of that variable.

Note that in this case, if we call the target variable to get its value and assign it to another variable, that other variable’s data type becomes of nullable type.

Example: accessing a nullable type in Kotlin using the if statement

fun main(){
    var names: Array<String?> = arrayOf("Jack","Ellen", "Omid","Monica",null, null ,null,null, "John")

    for (element in names){
        if (element != null){
            println("The value is: $element")
        }else{
            println("*The value is null*")
        }
    }
    
}

Output:

The value is: Jack

The value is: Ellen

The value is: Omid

The value is: Monica

*The value is null*

*The value is null*

*The value is null*

*The value is null*

The value is: John

Kotlin Nullables and Safe Call Operator

The safe call operator is a shorter way of checking the value of a nullable type variable to see if it has a null value or not. If the target variable wasn’t pointing to a null value, then it will allow us to continue and call any property or functions of the target object that the variable is pointing at. Otherwise, if the variable was pointing to a null value, nothing will happen and only the value null will return as a result.

Example: using safe call operator in order to access a value of nullable type

class Person (var firstName:String, var lastName:String){
    fun printFullName(){
        println("The full name is: $firstName $lastName")
    }
}
fun main(){
    var prs: Person? = null 
    var prs2:Person? = Person("John","Doe")
    
    prs?.printFullName() //This will return the value null because the prs variable holds a null value
    prs2?.printFullName()
}

Output:

The full name is: John Doe

In the Kotlin safe call operator section, we will talk in a greater detail about this operator, but in short, this is how we use this operator:

variableName?.memberName

Here the variableName? is the variable that is holding either a null value or an actual non-null value.

For example: prs? and prs2?

Here, the value of these variables is checked to see if they are pointing to a null value or not.

If they did, then this operator terminates the operation immediately and returns the value null.

So for the prs?.printFullName() we want to call the printFullName() function of the object that the prs variable is pointing at. But we can see that this variable has the value null and this value doesn’t have a function with such a name (printFullName)! So the safe call operator realizes this and immediately terminates the operation (before any call to the function happens) and simply returns the value null as a result.

But for the prs2? this variable’s value is not null. So for this reason the safe call operator allows the operation to proceeds and so the call to the printFullName() function happens at this time!

That’s how we got only one message on the output stream.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies