https://kotlinlang.org logo
#compose
Title
# compose
y

yschimke

12/05/2021, 10:20 AM
Is smart cast for nullable State fields something that could be improved in Compose? Seems like a case for https://youtrack.jetbrains.com/issue/KT-20294, The composition should run within a snapshot of the state system, where a field is null or not. Seems like the taskSeries should be known to be non-null.
Copy code
val taskSeries by viewModel.taskSeries(taskSeriesId).collectAsState(initial = null)

    if (taskSeries != null) {
                Text(text = taskSeries.name)
d

Didier Villevalois

12/05/2021, 10:52 AM
Hi @yschimke, how can
taskSeries
be not null during the first composition if you explicitely specify
null
as an initial value for your
collectAsState
?
y

yschimke

12/05/2021, 11:10 AM
The
if (taskSeries != null) {
check handles that, but this
Text(text = taskSeries.name)
shows the error
Smart cast to 'TaskSeries' is impossible, because 'taskSeries' is a property that has open or custom getter
I guess I'm asking whether Compose should do something similar to Kotlin contracts
d

Didier Villevalois

12/05/2021, 11:27 AM
Oh I am sorry. Reading your post, I though you wanted to get rid of this check. Please ignore my previous comment. I can't explain the error without more context.
s

sindrenm

12/05/2021, 1:19 PM
In this case, since you're dealing with a
val
on the Compose side, you could get rid of the property delegate and just do this:
Copy code
val taskSeries = viewModel.taskSeries(taskSeriesId).collectAsState(initial = null).value
That should help your smart casting along a little.
2 Views