https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sean Proctor

02/27/2022, 10:23 AM
Is there a more concise way to write this:
Copy code
val result = foo.method1()
    .let {
        if (condition) {
            it.method2()
        } else {
            it
        }
    }.method3()
a

Andromadus Naruto

02/27/2022, 10:55 AM
Can you give more context? Like the shape of the
foo
object...
1
k

Klitos Kyriacou

02/27/2022, 1:37 PM
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

Joffrey

02/27/2022, 10:54 PM
Is
foo
some sort of builder object that returns itself? In this case you could use
apply
instead of chaining
s

Sean Proctor

02/27/2022, 11:26 PM
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

Joffrey

02/27/2022, 11:30 PM
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

Tobias Suchalla

02/28/2022, 7:27 AM
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

Joffrey

02/28/2022, 8:45 AM
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

Sean Proctor

02/28/2022, 12:22 PM
Ah, perfect, thanks.