Sean Proctor
02/27/2022, 10:23 AMval result = foo.method1()
.let {
if (condition) {
it.method2()
} else {
it
}
}.method3()
Andromadus Naruto
02/27/2022, 10:55 AMfoo
object...Klitos Kyriacou
02/27/2022, 1:37 PMcondition
has no side effects and does not use any side effects resulting from the call to foo.method1()
then it shouldn't matter what order you evaluate condition
wrt foo.method1()
and thereforeyou can make it a bit more readable:
val result =
if (condition)
foo.method1().method2().method3()
else
foo.method1().method3()
Joffrey
02/27/2022, 10:54 PMfoo
some sort of builder object that returns itself? In this case you could use apply
instead of chainingSean Proctor
02/27/2022, 11:26 PMModifier
. I think it creates a new instance on each method call.Sean Proctor
02/27/2022, 11:27 PMmethod2
that depends on the condition.Joffrey
02/27/2022, 11:30 PMfun Foo.method2If(condition: Boolean) = if (condition) method2() else this
// then use it
val result = foo.method1().method2If(condition).method3()
Tobias Suchalla
02/28/2022, 7:27 AMinline fun Modifier.thenIf(
condition: Boolean,
then: Modifier.() -> Modifier
): Modifier = if (condition) then() else this
e.g.
Modifier
.size(10.dp)
.thenIf(condition) { padding(10.dp) }
.background(Color.Black)
Joffrey
02/28/2022, 8:45 AMletIf
function that does exactly that with any type, although I'm not sure it would be that usefulSean Proctor
02/28/2022, 12:22 PM