Safe calls(?.) vs Null checks(!!) in Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/safe-calls-vs-null-checks-in-kotlin/ and reposted on Medium on 14th Nov 2017.
var variable : CustomClass = CustomClass()
variable = null //compilation error
var nullableVariable : CustomClass? = CustomClass()
nullableVariable = null //works fine
variable.someMethodCall() //works fine as the compiler is sure that
//the variable can’t be null
nullableVariable.someMethodCall() //will highlight compilation error
//as compiler is not sure as
//nullVariable can be null.
if ( null != nullableVariable) {
nullableVariable.someMethodCall()
} else {
// fallback flow
}
Smart cast to ‘CustomClass’ is impossible, because ‘nullableVariable’ is a mutable property that could have been changed by this time.
nullableVariable?.someMethodCall()

Please continue reading at https://agrawalsuneet.github.io/blogs/safe-calls-vs-null-checks-in-kotlin/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store