Welcome to kotlin Series
In this post, we are going to discuss a very important topic of Kotlin. The topic is kotlin null safety.
I think you already heard this keyword, null safety, Kotlin is a null safety language. right?
what is the null safety? In kotlin by default, you can not assign a value of a variable as null. All the variable must have a value.
but if you want an assign a variable as null, you have to use?
code-
Thank you very much.
Happy coding
In this post, we are going to discuss a very important topic of Kotlin. The topic is kotlin null safety.
I think you already heard this keyword, null safety, Kotlin is a null safety language. right?
what is the null safety? In kotlin by default, you can not assign a value of a variable as null. All the variable must have a value.
but if you want an assign a variable as null, you have to use?
code-
val nullValue:String? = nullif you want to create a variable but want to assign a value later then use
var name:String? name = "shudipto"now print the value
println("Name: $name")output:
Name: shudiptonow assign this value to null
name = nullprint this new value
println(name)Output:
null
Note: if you want to set this variable must have value then use below code-print(name!!)now we create a function that returns null
//null return function fun returnNull():String? { return null }print this value:
println("Function: ${returnNull()}")Output:
println("Function: ${returnNull()}")now we use the force operator to assign the return value of this methods
val returnNull1:String ?= returnNull()now if we want to learn the length of this variable we can use length method
//val returnNull2 = returnNull1.lengthbut this line shows an error because the value of the variable is null. This is the advantage of kotlin. If you are in java the here this line program will be crashed. but in kotlin, we can do by this way without any crash
val returnNull2 = returnNull1?.length
Now, this program will not crash. but you can do another thing that is if the value is null then you can save a string or default value I am using a stringval returnNull2 = returnNull1?.length ?: "value is null"print the value
println("ReturnNull2: $returnNull2")output:
ReturnNull2: value is nullsee the variable value is null so the default value is assigned. you can also use this method for the specific data type variable:
val returnNull4:String = returnNull() ?: "No name"print the value:
println(returnNull4)Output:
No nameThat's it. Hope you understand the concept. This is very important in Android App development. It prevent some unexpected crash.
Thank you very much.
Happy coding