2

I have the following situation:

interface AbstractState {...}
interface SubState {...}

interface NiceInterface {
  var currentState: AbstractState
  ...
}

Furthermore I have a class which implements this interface.

class Class : NiceInterface {
  override var currentState: AbstractState = SubState()
}

This implies that I have to write the following at every use of it in the class:

(currentState as SubState).doSomething()

Is there a way to avoid the "as SubState" part? Or some kind of smart way to do it?

Like with generics:

interface => val currentStates: List<out AbstractState>
class     => override val currentStates = ArrayList<SubState>()
Punika
  • 275
  • 3
  • 14

1 Answers1

1

As Alexey Romanov said the problem with setter, so there is a workaround, replace var by val:

interface AbstractState {}
class SubState : AbstractState{}

interface NiceInterface {
    val currentState: AbstractState
}

class Class : NiceInterface {
    override val currentState: SubState by lazy {
        SubState()
    }
}

So now you don't need to cast:

currentState.doSomething()
Oleksandr Albul
  • 1,174
  • 14
  • 24