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")
}
fwiw I've also added extension methods that do something like this (
letIf
)
👍 1
m
Michael Böiers
04/20/2021, 7:47 PM
@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 }
Michael Böiers
04/20/2021, 8:03 PM
@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
Jonathan Olsson
04/21/2021, 7:35 AM
It would be pretty consistent with
takeIf
and
takeUnless
if all scope functions had an if/unless equivalent. I.e.