Programming with Kotlin null safety lesson 4

Words
173
Reading
1 min
Listen
Play
9y


Kotlin-logo.png


  


 In the previous lesson we talked about the definition of variables in kotlin and assigning a value to it But what if we wanted to define  a variable without assigning any value to it during the definition? We can do this in the following way:


 1-var OR val 


2- its name 


3-the tag: 


4- its type 


5-add a question mark ?


The question mark means that the value will be assigned later


 EX:


 var name:String?


 EX:


 fun main (args:Araay <String>)


 { 


        var name:String?


       name = "mark"


       print(name)


        name = null


         print(name!!) 


}

In this example, we defined a variable called name its type is string, then we assigned the "mark" value, and then ordered it to print on the screen. 


Then we assigned it a null value, and also print on the screen


  But the result of the program will be  (mark) only  because of the use of exclamation marks in the second print  print(name !!)


  which means Do not execute if the value is null 


 This process is called null safety