onTrue

Performs the given action if this Boolean is true. Returns the original Boolean unchanged.

This is a shorthand for if (this) { action(); true } else { 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 trySkipChar(): Boolean = (index < length).onTrue { ++index }

Similarly, onTrue can serve as a shorthand for .also { if (it) { action() } }. Example:

val someOperationFailed = operations.any {
it.hasFailed().onTrue {
log("Operation $it failed")
}
}

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. onTrue can help succinctly process such results:

tryStoreInDatabase().onTrue {
return StorageStatus.SUCCESS
}

Since Kotlin

2.5

See also