Fergus Hewson
09/26/2024, 9:29 PMFergus Hewson
09/27/2024, 3:00 AM@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
}
jw
09/27/2024, 4:22 AMFergus Hewson
09/27/2024, 6:22 AMOlivier Patry
09/27/2024, 6:29 AM.takeIf {}
or the like which are convenient sometimes, especially when you can benefit from non null smart cast on the object you reason aboutFergus Hewson
09/27/2024, 7:28 AMtad
09/27/2024, 8:58 PMlet
or takeIf
tad
09/27/2024, 8:59 PM