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
Fergus Hewson
09/27/2024, 3:00 AM
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
jw
09/27/2024, 4:22 AM
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
Fergus Hewson
09/27/2024, 6:22 AM
So these ideas are not idiomatic?
o
Olivier Patry
09/27/2024, 6:29 AM
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