Declare a variable that is not null
// 1. Declare a variable that is not null and cannot be assigned to null. By xiaojin on 7/24/21 9:32pm var name:String init {name = "Tom" Null can not be a value of a non-null type String by xiaojin on 7/24/21 9:33 PM name = null }Copy the code

When declaring a nonnull variable, if it is not initialized at definition time, it must be initialized later and cannot be assigned to NULL

Declare a variable that can be null
// 2, declare a null variable by xiaojin on 7/24/21 9:38 PM var tel:String? Init {// can be assigned to null by xiaojin on 7/24/21 9:40 PM tel = null Type, so need to use!! By Xiaojin on 7/24/21 9:42 PM call(tel!!) } fun call (num: String) {println (" in the ${num} dial-up..." )}Copy the code

Once we do this, we crash the program by throwing an exception when we use a non-null assertion on a variable with a value of NULL

Exception in thread "main" kotlin.KotlinNullPointerException
	at com.example.firstkotlin.koltin.NullType.<init>(NullType.kt:30)
	at com.example.firstkotlin.koltin.NullTypeKt.main(NullType.kt:45)
	at com.example.firstkotlin.koltin.NullTypeKt.main(NullType.kt)
Copy the code

So we usually recommend using the following method

// 2, declare a null variable by xiaojin on 7/24/21 9:38 PM var tel:String? By xiaojin on 7/24/21 9:40 PM tel = null; by xiaojin on 7/24/21 9:40 PM tel = null "1234567890" // We generally do not recommend using non-null assertions because they are very dangerous and will throw an exception if the variable is null by xiaojin on 7/24/21 9:44 PM call(tel? : "0")} fun call (num: String) {println (" in the ${num} dial-up..." )}Copy the code

Output bit:

Dial..... for 0Copy the code

In this example, the security call operator (? 🙂 checks the value on the left and returns it if it is not null. If it is, the next action is performed.

3, when nullable types are used with val
By xiaojin on 7/24/21 9:56pm val address:String? init { address = null if(address ! = null){// Please note that goHome requires a String argument instead of a String? , indicating that after passing the nonnull judgment, String? By xiaojin on 7/24/21 10:05 PM goHome(address)}} fun goHome(destination:String){println(" navigate to ${destination}") }Copy the code

The interesting thing is that nullable types that are decorated by val have their nullable properties removed after the non-nullable type is determined. This has to do with the fact that val, once assigned, cannot be modified. Of course, if you use var modification, it is not allowed.