Lesson 44: Null values ​​in variables Kotlin Programming language

Lesson 44: Null values ​​in variables Kotlin Programming language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

So far we have not analyzed how Kotlin Programming language treats null values (null) in the definition of variables.

In Kotlin Programming language, we treat separately the variables that allow us to store a null value and those that by their nature can not store it.

We have worked so far with variables that can not store a null value, we can easily check it with the following lines of code:

Lesson 44: Null values ​​in variables Kotlin Programming language - Lesson 44: Null values ​​in variables Kotlin Programming language - Lesson 44: Null values ​​in variables Kotlin Programming language -

The variable name must store a character string and by definition can not store a null value.

We can perfectly assign another object of type String, but not the value null:

    Var name: String
    Name = "Juan"
    Name = "Ana"

The same happens if we define variables of type Int, Float, IntArray etc:

    Var telefono: Int
    Phone = null // compilation error 
    Var array: IntArray = IntArray (5)
    Fix = null // compile error

To allow a variable to contain a null value, we must add the character “?” In the moment that we define the type of the variable (with this we indicate to the Kotlin Programming language compiler that are variables that allow to store the value null):

Fun main (args: Array <String>) {
    Var telefono: Int?
    Phone number = null
    Var array: IntArray? = IntArray (5)
    Fix = null
}

When working with variables that can store null values our code must verify the value that the variable stores:

Fun main (args: Array <String>) {
    Var name: String
    Print ("Enter your name:")
    Name = readLine () !!
    Println ("The name entered is $name")}

So far to make our programs simpler when loading data on the keyboard, we called the readLine() function and the operator !! At the end, this because the readLine function returns a String data type:

Public fun readLine(): String? = Stdin.readLine ()

If the readLine function returns a String? We can not store it in a String variable. To be able to copy a data that can store a null value in another one that can not do it we use the !! And should be avoided where possible.

We can now modify the previous program and define a String variable:

Fun main (args: Array <String>) {
    Var name: String?
    Print ("Enter your name:")
    Name = readLine ()
    Println ("Entered name is $name")
}

As we see now we do not have the operator !! At the end of the readLine call.

Nulls control

When working with variables that can store null value we can use if to verify if its value is other than null.

fun main (args: Array <String>) {
    var string1: String? = null
    var string2: String? = "Hello"
    if (string1!= null)
    println ("string1 stores $string1")
    else
    println ("string1 points to null")
    if (string2 != null)
    println ("string2 stores $string2")
    else
    println ("string2 points to null")
}

Using if we verify whether the variable stores a null or a value other than null and act on the stored value:

    If (string1! = Null)
        Println ("string1 stores $string1")
    Else
        Println ("string1 points to null")

We can try to call its methods and properties without an error when we have the “?” Followed by the variable:

    Var string1: String? = Null
    Println (string1? .length)

A null is printed on the screen but an error is not generated since the length property of the String class is not accessed, this is because string1 stores a null.

This syntax is very convenient if we have calls like:

If (employee1?.dataPersonal?.phone?! = Null)

Any of the objects that point to null then the if is false.

An example of access would be:

data class PersonalData (val name: String, val phone: Int?)
data class Employee (val EmployeeNum: Int, val dataPersonal: PersonalData?)

fun main (args: Array <String>) {
    var employee1: Employee?
    employee1 = Employee (100, PersonalData ("Juan", null))
    if (employee1?.dataPersonal?.phone == null)
    println ("The employee does not have a phone")
    else
    println ("The employee's phone number is ${employee1?.dataPersonal?.phone}")
}

With this syntax we say that the variable employee1 can store null (for example if the company does not have employees):

    Var employee1: Employee?

The personal data property of the Employee class can store null (for example if we do not have the employee’s personal data):

Data class Employee (val EmployeeNum: Int, val dataPersonal: Personal data?)

The PersonalData class has a phone property that can store null (for example if the employee does not have a phone):

Data class PersonalData (val name: String, val phone: Int?)

To print the telephone of an employee, we must check if the employee exists, if he has stored his personal data and if he has a telephone, an approximation with several if would be:

    If (employee1! = Null)
        If (employee1.dataPersonal! = Null)
            If (employee1.dataPersonal? .phone = null)
                Println ("The employee's phone number is ${personal1.dates.?phone}")

Analyzing, if they have stored values other than null until you reach the property of the phone to display it.

But in Kotlin the most concise syntax for accessing the phone is:

    If (employee1?.dataPersonal?.phone == null)
        Println ("The employee does not have a phone")
    Else
        Println ("The employee's phone number is ${employee1?.dataPersonal?.phone}")

Either employee1 stores null or the personal data property stores null then returns null the expression.

About The Author

Related posts

Leave a Reply