Suppose I define a class with a nullable property
class ABC {
var myProperty: String? = null
}
Is there a way to default it to null value? Maybe something similar to SCALA?
var myProperty: String? = _ // compilation error
or simply:
var myProperty: String? // compilation error
I know we could have used a lateinit variable that from Kotlin 1.2 can be later checked for initilization like so:
lateinit var myProperty: String
if (::myProperty.isInitialized) {
//value is not-null
}
So is lateinit the preferred way? Is defaulting to null value possible or it's omitted on purpose?
In an effort to rid the world of NullPointerException , variable types in Kotlin don't allow the assignment of null . If you need a variable that can be null, declare it nullable by adding ? at the end of its type. Declares a non- null String variable.
Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.
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.
Null Comparisons are simple but number of nested if-else expression could be burdensome. So, Kotlin has a Safe call operator, ?. that reduces this complexity and execute an action only when the specific reference holds a non-null value.. It allows us to combine a null-check and a method call in a single expression.
Kotlin intentionally requires you to initialize all properties explicitly. There is no shorthand syntax. For a property of a nullable type, the preferred way is not to use lateinit
, but to declare it with a null
initializer.
The isInitialized
method for lateinit
properties is designed to handle complex cases like cleanup of resources; it's not intended to be used as a replacement for a null
check for users who want to save on writing = null
as part of a property declaration.
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