```when (result) { Result.Loading -> {} ...
# announcements
k
Copy code
when (result) {
    Result.Loading -> {}
    is Result.Success -> SomeScreen(data= (dataResult as Result.Success<List<SomeData>>).value)
    is Result.Error -> {}
}
How do I prevent casting type on Success? My Result class
Copy code
sealed class Result<out T> {
    object Loading : Result<Nothing>()
    data class Error(val message: String) : Result<Nothing>()
    data class Success<T>(val value: T) : Result<T>()
}
i
If your
result
variable has type
Result<List<SomeData>>
it works as you expect https://pl.kotl.in/FK3qHAXQD
k
I get:
Copy code
Smart cast to 'Result.Success<List<SomeData>>' is impossible, because 'result' is a property that has open or custom getter
I am using flow from ViewModel to get the state in compose.
i
I guess you can save your variable into a local one so that compiler can smart cast it
Copy code
val resultLocal = result
when(resultLocal) {
  //use resultLocal
}
k
Yep, that works. Why does this happen? Can I avoid it?
i
That's a correct behavior from the compiler perspective. Property which is open can be overridden and custom getter may produce different result on each invocation so you can't rely on it in such cases
2
k
Thanks Ivan
m
You may also do
Copy code
when(val resultLocal = result) {
  //use resultLocal
}
👍 2
i
In your original post i see
result
in
when
parentheses, but when you cast - you cast
dataResult
Smartcast works for
when
parentheses content
k
I changed values, sry, was not consistent
@mcpiroman solution works
i
Note that you can write first line of
when
cases as
Result.Loading -> {}
also as
is Result.Loading -> {}
. In first case works
equals
, in second
instanceof
. First case only possible for
object
classes
🙌 1