0

Consider this nice utility extension function i wanted to use :

inline infix fun <T> T?.otherwise(other: () -> Unit): T? {
    if (this != null) return this
    other()
    return null
}

It could be very useful for logging stuff when expressions evaluated to null for example:

val x: Any? = null
x?.let { doSomeStuff() } otherwise {Log.d(TAG,"Otherwise happened")}

but I see that it wont work for :

val x: Any? = null
x?.otherwise {Log.d(TAG,"Otherwise happened")}

see here for running example

Well when thinking about it i guess that makes sense that if x is null the ? makes the postfix not be executed, but i dont understand why the let in the first example is any different?

Is it possible to fix the utility to be more robust and work without having to have let in the chain?