The code below will not compile because the variable myType
can be null. Is there a way of executing a with
block for nullable types in Kotlin?
val myType: MyType? = null
with(myType) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
when using methods which return a nullable value for which you have a default or alternative, use the Elvis operator to provide a default value. In the case of a Map use the getOrElse() which allows a default value to be generated instead of Map method get() which returns a nullable value.
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.
TypeScript Nullable is a special type null that has the value null. TypeScript Null is much like void, i.e. not useful on its own. By default, null is a subtype of all other subtypes which means a user can assign null to any of the data types like string, number, etc.
Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.
You can convert a nullable type to a non-nullable type with the suffix !!
:
with(myType!!) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
If the value is indeed null, it will throw a NullPointerException
, so this should generally be avoided.
A better way to do this is to make the execution of the code block dependent on the value being non-null by making a null-safe call and using the apply
extension function instead of with
:
myType?.apply {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
Yet another option is to check if the value is non-null with an if
statement. The compiler will insert a smart cast to a non-nullable type inside the if-block:
if (myType != null) {
with(myType) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
}
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