https://kotlinlang.org logo
Title
b

Ben Madore

10/11/2019, 8:31 PM
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:
fun <T> T?.whenNull(block: T?.() -> Unit): T? {
    if (this == null) {
        block()
    }
    return this
}
to be used like:
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?
yep, looks like it would have to be:
return getFoo() ?: run {
  <http://log.info|log.info> {"can't find a foo"}
  null
}
which isn’t particularly expressive imo
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
b

Ben Madore

10/11/2019, 9:11 PM
where’s the fun in that 😄
i

ilya.gorbunov

10/11/2019, 10:39 PM
also
function suits such side checks well:
return getFoo().also {
    if (it == null) <http://log.info|log.info>("Can't find foo")
}