androidkotlinandroid-jetpack-compose

"Unresolved reference: copy" if using || operator in data class check


Having this uistate:

sealed interface BusStopsDBScreenUiState {
    val message: StringResource?
    data class Loading(override val message: StringResource? = null) : BusStopsDBScreenUiState
    data class Error(override val message: StringResource? = null) : BusStopsDBScreenUiState
    data class Success(val data: List<BusStop>, override val message: StringResource? = null) : BusStopsDBScreenUiState
}

And this check:

if ((currentState is BusStopsDBScreenUiState.Success) || (currentState is BusStopsDBScreenUiState.Error))
    _uiState.value = currentState.copy(message = null)
}

I'm getting this error on copy call:

Unresolved reference: copy

If I remove the || operator and let simply if (currentState is BusStopsDBScreenUiState.Success) then copy doesn't give that error anymore.

How it's possible? how can this be solved?


Solution

  • You can only use copy on a data class.

    currentState cannot be smart-cast to any specific data class because it could be either Success or Error. So its type is the common super type BusStopsDBScreenUiState, and that is an interface and not a data class, hence no copy function.

    That changes when you only test for a single data class type (f.e. Success, without using ||), then the compiler can smart-cast currentState to that type which is a data class. And then you can use copy.