How to use Kotlin `with` expression for types with null value

The code below will not compile because the variable myType may be null. Is there a way to execute a with block for types with a null value in Kotlin?

  val myType: MyType? = null with(myType) { aMethodThatBelongsToMyType() anotherMemberMethod() } 
+10
source share
2 answers

You can convert a type with a null type to a type with a null value with a suffix !! :

 with(myType!!) { aMethodThatBelongsToMyType() anotherMemberMethod() } 

If the value is really null, it will throw a NullPointerException , so this should usually be avoided.

The best way to do this is to make code block execution dependent on a non-zero value by creating a null safe call and using the apply extension function instead of with :

 myType?.apply { aMethodThatBelongsToMyType() anotherMemberMethod() } 

Another option is to check to see if null is set to with the if . The compiler will insert smart casting into a non-null type inside the if-block:

 if (myType != null) { with(myType) { aMethodThatBelongsToMyType() anotherMemberMethod() } } 
+17
source

You can define your own with function, which takes on nullable values, and then determines whether it will actually execute based on whether the object is null.

Like this:

 fun <T, R> with(receiver: T?, block: T.() -> R): R? { return if(receiver == null) null else receiver.block() } 

Then you can name the code as you wanted in the example, no problem, and the result will be null if what you pass is null .

Or, if the code block should (and could) be executed anyway, even if myType is null , you should define it like this:

 fun <T, R> with(receiver: T?, block: T?.() -> R): R { return receiver.block() } 
+2
source

All Articles