Wednesday, May 20, 2020

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :-

Safe call  ( ? )    use it if you don't mind getting null values
Not Null Insertion ( !! )  use if you are sure that value is not null otherwise throw Nullpointer Exception
Elvis ( ?: )  goes with function when values is not null, otherwise decided value
Safe call with let ( ?.Let { .. } ) execute the block only value is not null

In Android, we mostly use safe call and not null insertion.

eg :-

fun main(args:Array<String>) {
    var s: String? = null                //safe call

    println("The lenght of name is ${s?.length}")


    s?.let {                            //safe call with let
        println("The length of name is ${s.length}")
    }

    var len = {            // same below code as elvis
        if (s != null) 
            s.length
        else
            -1
    }

    var len1 = s?.length?:-1           //elvis
    println("The length of name is ${len1}")

    println("the length of name is ${s!!.length}")   //not null insertion
}

Lazy keyword :-

prevent unnecessary initialization of object.
can be var/val , null/not null and thread safe

 val pi: Float by lazy {
    3.14f
}

fun main (args:Array<String>)
{
 println("some initial code..")
 var a =pi*3*3
 var b = pi*a*a
 println("some more code...")
}


LateInit Keyword :-

Initialize the variable later, when used otherthrow uninitializedpropertyAccess Exception.
Allowed with only not null values
promise to compiler that value will initialize in Future 

** Mainly Helpful in Android Programming

fun main(args:Array<String>)
{
    var a = animal();
//    a.name = "Cat"
//println("name : ${a.name}")

    a.check()
}

class animal
{
    lateinit var name:String   //use of late init
    fun check()
    {
        name = "Monkey"
        println("name in function : ${name}")
    }
}



















No comments:

Post a Comment

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :- Safe call  ( ? )    use it if you don't mind getting null values Not Null Insertion ( !! )  use if you are sure that val...