kotlinimmutabilitymutablebacking-field

How to use Kotlin backing field with Channel and Flow?


I am playing with the new backing field feature introduced in Kotlin 2.0, however I am encountering some problem when using it on data type that is not a superclass/subclass of one and another.

private val _youTubeVideosState = Channel<YouTubeVideosState>()

val youTubeVideosState = _youTubeVideosState.receiveAsFlow()

How to convert this with using backing field? I tried the below but wasn't able to access the send() method of Channel.

val youTubeVideosState: Flow<YouTubeVideosState>
    field = Channel<YouTubeVideosState>().receiveAsFlow()

If I tried the below it is complaining about the type not being superclass of subclass.

val youTubeVideosState: Flow<YouTubeVideosState>
        field = Channel<YouTubeVideosState>()

Solution

  • This doesn’t make sense to do. A Flow and Channel are not in a hierarchical relationship. The property type must be a supertype of the field type, because the way this feature works is that the value in the field is merely upcast to the type of the property. It’s still the same instance/reference.

    receiveAsFlow() creates a new instance of a different class. That instance has to be stored somewhere, and it cannot be in the same backing field as the channel, so two properties are necessary. A property can’t have two backing fields.