Kotlin | Null Safety
- Get link
- X
- Other Apps
Kotlin tries to solve most infamous java problem which is "NullPointer Exception". There is less possibility of of seeing this exception in Kotlin but due to developer mistake or 3rd party library issues we might see this exception in Kotlin program as well.
Let's see it in action:
Kotlin allows you to define two type of references nullable and non-nullable, this give programmer information about usage of variable at compile time.
Non-nullable string:
fun main(args: Array<String>) { var myName : String = "Amit" myName = null // Compilation Error var nullableName : String ? = "This is nullable Variable" nullableName = null // Compiler is not complaining }
It will be unsafe to do method call on nullable object types and compiler will prevent us to do so.
fun main(args: Array<String>) { var nullableName : String ? = "This is nullable Variable" //UnSafe method call println(nullableName.length) // This will not compile }
fun main(args: Array<String>) { var nullableName : String ? = "This is nullable Variable" //Safe Call 1. With null check if(nullableName!= null) { println(nullableName.length) } }
2. Use of ?. operator
fun main(args: Array<String>) { var nullableName : String ? = "This is nullable Variable" //Other way to write conditional println(nullableName?.length) }
In practical, there is one more better way to use nullable references with default value, this is called Elvis operator. Below is the example of Elvis operator where variable "length" will be assigned value of nullableName length if it is not null otherwise it will be assigned value "-1" In other words, The Elvis operator will evaluate the left expression and will return it if it’s not null else will evaluate the right side expression.
fun main(args: Array<String>) { var nullableName : String ? = "This is nullable Variable" //Elvis operator // below exp will return length or -1 var length = nullableName?.length ?: -1 }
It is possible to see null pointer exception in Kotlin as well, that is the reason we should use "!!" operator with utmost care. We should only use "!!" operator if we are 100% sure that object reference will never be null.
fun main(args: Array<String>) { var nullableName : String ? = "This is nullable Variable" // !! operator, Use with care, this can throw null pointer exception println(nullableName!!.length) }
I hope you like this, if so please subscribe to blog for upcoming posts in your email box.
All the code samples can be found here.
