Yan Pujante
03/29/2021, 4:54 PM@Composable
fun EditPartUI(part: Part, onDismiss: () -> Unit) { /* */ }
@Composable
fun PartXX() {
var pendingPartCreate by remember { mutableStateOf<Part?>(null) }
if(pendingPartCreate == null) {
ScrollableTab(
onFabAction = { pendingPartCreate = Part() }) {
// ....
}
} else {
EditPartUI(pendingPartCreate!!, onDismiss = { pendingPartCreate = null} )
}
}
The else
branch does not compile unless I use pendingPartCreate!!
(smart cast does not work). So is the compiler not smart enough to detect the fact that it cannot change? Or is the compiler rightfully wants to prevent me from shooting myself in the foot?TheMrCodes
03/29/2021, 4:56 PMYan Pujante
03/29/2021, 4:57 PMTheMrCodes
03/29/2021, 4:59 PM[...]
val currentPendingPart = pendingPartCreate
if (currentPendingPart == null) {
// casted to null
} else {
// casted to notnullable Part
}
[...]
jim
03/29/2021, 5:10 PMEditPartUI
might invoke the onDismiss
lambda. By convention, Compose widgets typically only invoke such callbacks on the main thread in response to a UI event, but this is not guaranteed by any system that the compiler can depend upon. In particular, the EditPartUI
widget might launch a thread and invoke that lambda between the null check and the usage.Yan Pujante
03/29/2021, 5:12 PMalbertosh
03/30/2021, 7:00 AMI am not launching any threadYou know it. The compiler doesn’t. So it goes for a conservative approach. In the end,
!!
operator is just that, you telling the compiler that it’s OK to use a nullable var without any check because you know that it won’t be null