Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Kotlin's `with` expression for nullable types

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()            
    }
like image 562
memoizr Avatar asked Mar 01 '16 12:03

memoizr


People also ask

What is the idiomatic way to deal with nullable values referencing or converting them?

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.

What is the correct way to initialize a nullable variable?

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.

Can TS number be null?

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.

How do I assign a value to null in Kotlin?

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.


1 Answers

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()            
    }
}
like image 198
Ingo Kegel Avatar answered Nov 08 '22 22:11

Ingo Kegel