Kotlin support Null safety, that means we can declare a varible can hold null value or not. By supporting of this null safety compiler can detect the NullPointer Exception errors at compile time. This reduce the NullPointer Exceptions at run time. All varibles in Kotlin are null safety, when we try to declare varibale with null vale will throw error at compile time
var intro: String = "Hello, World"
intro = null // Compilation Error
so if want to allow null valu for the variable we need to declare the variable like below
var intro: String? = "Hello, World"
intro = null
We know NullPointer exceptions will occure when we accessing the null variables. Kotlin not allow accessing the Methods or property on nullable variables.
Nullable Types in Kotlin
Kotlin provides the below ways to access the null varaibles. Checking the Null condition
var str:String="Kotlin"
if(str!=null){
println("Welcome to $str")
}else
{
println("Welcome to Guest")
}
Output : Welcome to Kotlin
Safe Operator ?By define the variable with ? operator
var str:String?="Kotlin"
str=null
str?.length
output : null
is same as
if(str!=null)
{
println(str.length)
}
else
{
println(null)
}
if we want to execute the statement only if the variable non null then we have to use let.
var str:String?=null
str?.let{ println(str.length) }
//Prints Nothing
The above expression will execute only the str value is not null
If we want to provide default value when the varoibale get null,
to get the default value we need define statement like below
var len=str.lenth ?: 0