Is there a more concise way to write this: ```val ...
# getting-started
s
Is there a more concise way to write this:
Copy code
val result = foo.method1()
    .let {
        if (condition) {
            it.method2()
        } else {
            it
        }
    }.method3()
a
Can you give more context? Like the shape of the
foo
object...
1
k
If
condition
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:
Copy code
val result =
    if (condition)
        foo.method1().method2().method3()
    else
        foo.method1().method3()
j
Is
foo
some sort of builder object that returns itself? In this case you could use
apply
instead of chaining
s
Specifically, it's a compose
Modifier
. I think it creates a new instance on each method call.
I don't think repeating methods is more readable, particularly because it's
method2
that depends on the condition.
j
Well then the most readable I can think of is to just add an extension function:
Copy code
fun Foo.method2If(condition: Boolean) = if (condition) method2() else this

// then use it
val result = foo.method1().method2If(condition).method3()
t
If it's for modifiers and you want a general solution instead of hardcoding method2, there is also:
Copy code
inline fun Modifier.thenIf(
    condition: Boolean,
    then: Modifier.() -> Modifier
): Modifier = if (condition) then() else this
e.g.
Copy code
Modifier
    .size(10.dp)
    .thenIf(condition) { padding(10.dp) }
    .background(Color.Black)
j
You can even go one step further and create a generic
letIf
function that does exactly that with any type, although I'm not sure it would be that useful
s
Ah, perfect, thanks.