Kotlin / KEEP

Kotlin Evolution and Enhancement Process
Apache License 2.0
3.29k stars 357 forks source link

Why interface does not support protected modifier? #330

Closed semenoh closed 1 year ago

semenoh commented 1 year ago

I'm trying to extract some functionality to delegate and it would be nice if interface support protected modifier but IDEA and compiler does not allow me to do this. Here is my case: ViewModel has a StateFlow<Boolean> where it notifies View That it should display loader. As this functionality is common to multiple views and corresponding view-models and it is a good practice to prefer composition over inheritance I'd like to make it by delegation like this:

class ViewModel(repo: Repo) : WithLoader by WithLoaderDelegate() {
  suspend fun getSomeData() {
    withLoader {
        repo.getSomeData()
    }
  }
}

interface WithLoader {
  val showLoader: StateFlow<Boolean>

  protected withLoadr(action: ()->Unit)
}

class WithLoaderDelegate: WithLoader {
  private val _showLoader = MutableStateFlow<Boolean>(false)
  override val showLoader = _showLoader.asStateFlow()

  override protected suspend fun withLoader(action: ()->Unit) {
    _withLoader.emit(true)
    try {
      action()
    } finally {
      _withLoader.emit(false)
    }
  }
}

Then I hope to be able to collect viewModel.showLoader flow but should not see viewModel.withLoader() function.

Similar thing could be done for error flow and other scenarious.

elizarov commented 1 year ago

This issue tracker is for logging on going language changes. See https://github.com/Kotlin/KEEP/blob/master/README.md. Please, open http://kotl.in/issue with your problem or proposal.