Kotlin Null Safety

Kotlin provides null safety in application. Null safety works on variables accepting null or not.NullpointerException is thrown the particular exception while sometimes application failure or system crashes. If anybody has been programming in Java or another, that concept is null. Kotlin compiler also has a null pointer exception if it finds any null reference in the code.

Nullable and Non-nullable types in kotlin-

  • Kotlin type system of two types of reference non-null references and nullable references.
  • A variable of type string can not hold null values. if we try to assign null then give a compile time error.

Kotlin program of non-nullable type

var m1:String =”CandidRoot solution”

m1=null //compilation error

 m1 is a string variable but can not hold a nullable value if assigning a null value in a variable then getting a compilation error.

              Or 

Var m1:String? “Condidroot solution”

m1=null //okay

print(m1)

M1 is a variable assigned with (?)  then the variable allowed null value at not getting error.

fun main(args: Array<String>){

    // variable is declared

    var m1 : String = "Candidroot solution"

 

    //m1 = null  // gives compiler error

   

    print("string s1 is: "+s1)

}

Output

CandidRoot solution

 

Above example m1 variable if assigned null then gets an error while the compiler is.

Kotlin program of nullable type

fun main(args: Array<String>){

    // variable is declared

    var m1 : String? = "CandidRoot solution"

 

    m1 = null  // no compiler error

   

    print("string s1 is: "+s1)

}

Output

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?

 

Elvis operator(?:)

The Elvis operator is used to return a null-value default value when the original variable is null.

Val subject=subjectname?: “Hello, how are you ?”

 

Val name= if(subject !=null)

             Subject

else

            “Hello, how are you ?”

 

For example, if the subject value is null then print “Hello , How are you ?” 

 

Not null assertion : !! Operator

 

The !! operator holds not null value in variable but assigns null value then throws an exception of NullPointerException.

 

fun main(args: Array<String>) {

var str : String? = "Condidroot solution"

println(str!!.length)

str = null

}

Output

19

Happy Coding!


365Bloggy May 8, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive