You could define your own with
function that accepts nullables, then determines whether to actually run 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 call the code the way you wanted to in the example with no issues, and the result will equal null
if what you pass in is null
.
Or, if the code block should (and could) be run either way, even if myType
is null
, then you'd define it like this instead:
fun <T, R> with(receiver: T?, block: T?.() -> R): R {
return receiver.block()
}
myType != null
? Kotlin smart casts should handle it.with
is not an operator but a function with two arguments of typesT
andT.() -> R
, so its usage is the same to usage of any other function. Seewith
documentation: kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html