i asked something similar a while back, but this is slightly different.
is there a standard extension function that takes a block, and only executes that block if receiver is null. something like:
Copy code
fun <T> T?.whenNull(block: T?.() -> Unit): T? {
if (this == null) {
block()
}
return this
}
to be used like:
Copy code
return getFoo().whenNull {
<http://log.info|log.info> {"can't find a foo"}
}
j
jw
10/11/2019, 8:31 PM
?: run { .. }
b
Ben Madore
10/11/2019, 8:35 PM
but
<http://log.info|log.info>
returns Unit, so i’d need to return a null from the run, ya?
Ben Madore
10/11/2019, 8:37 PM
yep, looks like it would have to be:
Copy code
return getFoo() ?: run {
<http://log.info|log.info> {"can't find a foo"}
null
}
which isn’t particularly expressive imo
Ben Madore
10/11/2019, 8:37 PM
i’m fine with using my own function, just didn’t know if there was a built-in
j
jw
10/11/2019, 8:44 PM
seems like you should just assign a local and do a normal null check