Hey, looking for clean ways to return composables ...
# compose
f
Hey, looking for clean ways to return composables based on nullability and predicates as opposed to if else statements. Take a look at the example below and let mw know what you think?
🧵 1
Copy code
@Composable
fun example() {
    val label: String? = null
    // annoying
    OutlinedTextField(
        value = "",
        onValueChange = {},
        label = if (label != null) {
            { Text(text = "label") }
        } else null
    )
    // Clean
    OutlinedTextField(
        value = "",
        onValueChange = {},
        label = label.letCompose { Text(text = "$it") }
    )
}

@Composable
private fun <T> T?.letCompose(
    block: @Composable (T) -> Unit
): (@Composable () -> Unit)? {
    return if (this != null) {
        @Composable {
            block(this)
        }
    } else null
}

@Composable
private fun Boolean?.ifCompose(
    block: @Composable (Boolean) -> Unit
): @Composable (() -> Unit)? {
    return if (this != null && this) {
        @Composable {
            block(this)
        }
    } else null
}

@Composable
fun test() {
    var a: Boolean? = null
    a.ifCompose { Text(text = "$it") } // Won't return composable
    a = false
    a.ifCompose { Text(text = "$it") } // Won't return composable
    a = true
    a.ifCompose { Text(text = "$it") } // Will return composable

    var b: String? = null
    b.letCompose { Text(text = it) } // Won't return composable
    b = "s"
    b.letCompose { Text(text = it) } // Will return composable
}
j
Part of the whole point of how Compose was designed was so that you can use imperative control flow rather than functional idioms.
👍 1
👍🏾 1
f
So these ideas are not idiomatic?
o
I see this similar to things like
.takeIf {}
or the like which are convenient sometimes, especially when you can benefit from non null smart cast on the object you reason about
f
it basically is takeIf / let but for composables
t
You can also return a lambda from
let
or
takeIf
Just double up the curly braces