I am currently in the process of learning Kotlin to replace Java in my android applications but am struggling with null safety.
I am getting familiar with the process of the handling null and non-null variables, however, I am still unsure of "best practice" in terms of the implementation null/non-null variables in Kotlin.
For example, in Java I would have written something like:
UserAccount account;
if (account == null) {
openLogin();
}
I understand I can replicate this in Kotlin but it seems as though the language is designed to avoid practice like this. How would I go about implementing this system through Kotlin, should I be adding a nullable variable?
I understand I can replicate this in Kotlin but it seems as though the language is designed to avoid practice like this.
Please note the distinction between a language without nulls and a null-safe language. Kotlin is the latter, which means it welcomes and embraces the null
value, but, as opposed to a language like Java, puts a leash on it.
Kotlin offers you syntax to handle nullable types in a concise, readable and safe manner. For your example,
if (account == null){
openLogin();
}
you can use this idiom:
account ?: openLogin()
At other moments you'll want to either act upon a non-null account
or just skip that part of the code if it's null
. Then you can use the optional derefence ?.
:
account?.userName?.also { println("Username is $it") }