onFalse
Performs the given action if this Boolean is false. Returns the original Boolean unchanged.
This is a shorthand for if (this) { true } else { action(); false }.
Usage
Performing an action while returning a Boolean
Occasionally, a function needs to compute a Boolean indicating if an operation should be performed.
fun tryAllocate(): Boolean {
val cell = allocateCell()
return allocateImpl(cell).onFalse {
cell.release()
}
}Content copied to clipboard
Similarly, onFalse can serve as a shorthand for .also { if (!it) { action() } }. Example:
val allOperationsSucceeded = operations.all {
it.hasSucceeded().onFalse {
log("Operation $it failed")
}
}Content copied to clipboard
Acting on the result of a Boolean-returning operation
Some operations indicate their success or failure by returning a Boolean rather than throwing an exception, returning null, or returning a Result. onFalse can help succinctly process such results:
tryStoreInDatabase().onFalse {
processError(queryDatabaseError())
}Content copied to clipboard