Today I looked for something like a conditional le...
# announcements
m
Today I looked for something like a conditional let or run, but found nothing. How about this - would something like it make sense in the standard library? https://pl.kotl.in/EI387hmPU
Copy code
inline 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")
}
y
Couldn't
"Foo".takeIf { ALL_TO_LOWER }?.run { toLowerCase() }
work maybe?
n
fwiw I've also added extension methods that do something like this (
letIf
)
đź‘Ť 1
m
@Youssef Shoaib [MOD] No, that would return a nullable type. And I wanted to get rid of the double lambdas or the nested if. This works, but is much less readable IMHO:
"Foo".run { if (ALL_TO_LOWER) toLowerCase() else this }
@nanodeath Yes, maybe I should drop the fancy name and stick with one of the existing scope functions. In this case it would then be
runIf
. It’s possible to do it let-style, but then we end up with two `it`s :-)
j
It would be pretty consistent with
takeIf
and
takeUnless
if all scope functions had an if/unless equivalent. I.e.
letIf
,
letUnless
,
applyIf
,
applyUnless
,
...
.