Saturday, August 19, 2017

Kotlin null safety

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-
val nullValue:String? = null
if 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: shudipto
now assign this value to null
name = null
print 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.length
but 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 string
val returnNull2 = returnNull1?.length ?: "value is null"
print the value
println("ReturnNull2: $returnNull2")
output:
ReturnNull2: value is null
see 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 name
That'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

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :