I have recently reviewed some kotlin codes, All nullable field initialized as null.
What is the difference between val x : String? = null
and val x : String?
Should we initialize the nullable fields as null?
Use the ?: Elvis operator safe-call operator returns null . It's similar to an if/else expression, but in a more idiomatic way. If the variable isn't null , the expression before the ?: Elvis operator executes. If the variable is null , the expression after the ?: Elvis operator executes.
Kotlin does not require you to mention the type of a variable when declaring it (thanks to type inference). A variable val must be initialized in the same block of code in which it was declared.
Nullable and Non-Nullable Types in Kotlin – If we try to assign null to the variable, it gives compiler error.
In kotlin, declaration of variable is different from java as kotlin is null safe language. You have to declare variable nullable. Only then its value can be null. To access nullable values you have to use !! or ? with variable names.
A property must be initialized. Therefore you have to do the initialization var x : String? = null
. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?
.
Alternatively you can use lateinit
, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With