# Kotlin Nullability ###### tags: `Kotlin` `Null` [TOC] ## ? Operator By stating a variable is optional(?), this variable can be null. ```kotlin= var nonNullable: String = "Lily" var isNullable: String? = null nonNullable = null //Compilation Error isNullable = null //OK because it is optional variable ``` For **optional variables**, we will have to check for its nullability when we try to access its information. ```kotlin= var nonNullable: String = "Lily" var isNullable: String? = null nonNullable.length isNullable?.length ``` ## Aritmetic Operators on null values | Operation | Non Null Operation | Replacement Method | | -------- | -------- | -------- | | Addition | + | ?.plus() | | Substraction | - | ?.minus() | | Multiplication | * | ?.times() | | Divisor | / | ?.div() | | Remainder | % | ?.rem() | ## Elvis Operator (?:) Guaratess a result return, if is null it returns the default value given, if not just give the original value. ```kotlin= var isNullable: String? = null println(isNullable?:"This String is null") println(isNullable?:"Null".length) ``` ## Non null assertion (!!) We use this when we believe that the value is definitely non null. Unless we are 100% sure, we will try to avoid using it, as it has high possibility to give us a crash if the value is null. ```kotlin= var isNullable: String? = null println(isNullable!!) //CRASH cannot assert a null value var isNullable = "non Null" println(isNullable!!) // It's alright as there is a value inside ``` ## lateinit var **lateinit var** is used when you do not especify the variable from the beginning, and you expect to instance it later. ### Wrong Practice > **BE CAREFUL** [color=red] > **NEVER** use == null to check a lateinit var, they are expected to be instanced, therefore if you check it like this you will 100% crash by getting **UninitializedPropertyAccessException**. ```kotlin=== private lateinit var apiService : RetrofitApi fun getInstance(addHeader: Boolean) : RetrofitApi{ if(apiService == null){ synchronized(RetrofitApi::class.java){ makeService() } } return apiService } //Result: //kotlin.UninitializedPropertyAccessException: lateinit property apiService has not been initialized ``` ### Right Practice >**PLEASE USE** >**::variable.isInitialized** to check whether lateinit was initialized or not.[color=green] ```kotlin=== private lateinit var apiService : RetrofitApi private lateinit var apiServiceHeader : RetrofitApi fun getInstance(addHeader: Boolean) : RetrofitApi{ if(!::apiService.isInitialized || !::apiServiceHeader.isInitialized ){ synchronized(RetrofitApi::class.java){ makeService() } } return if(addHeader){ apiServiceHeader } else { apiService } } ```