Michael Böiers
04/20/2021, 2:50 PMinline fun <T> T.thatIf(condition: Boolean, block: T.() -> T) = if (!condition) this else block()
inline fun <T, R> T.thatIf(condition: Boolean, default: R, block: T.() -> R) = if (!condition) default else block()
inline fun <T> T.letIf(condition: Boolean, block: (T) -> T) = if (!condition) this else block(this)
inline fun <T, R> T.letIf(condition: Boolean, default: R, block: (T) -> R) = if (!condition) default else block(this)
val ALL_TO_LOWER = true
val APPEND_SIZE = false
fun main() {
val foo = "Foo"
.thatIf(ALL_TO_LOWER) { toLowerCase() }
.thatIf(APPEND_SIZE) { "$this ($length)"}
val bar = "Bar"
.letIf(ALL_TO_LOWER) { it.toLowerCase() }
.letIf(APPEND_SIZE) { "$it (${it.length})"}
println("$foo $bar")
}
Youssef Shoaib [MOD]
04/20/2021, 4:12 PM"Foo".takeIf { ALL_TO_LOWER }?.run { toLowerCase() }
work maybe?nanodeath
04/20/2021, 5:19 PMletIf
)Michael Böiers
04/20/2021, 7:47 PM"Foo".run { if (ALL_TO_LOWER) toLowerCase() else this }
Michael Böiers
04/20/2021, 8:03 PMrunIf
. It’s possible to do it let-style, but then we end up with two `it`s :-)Jonathan Olsson
04/21/2021, 7:35 AMtakeIf
and takeUnless
if all scope functions had an if/unless equivalent. I.e. letIf
, letUnless
, applyIf
, applyUnless
, ...
.