Eric Martori
07/13/2019, 11:14 AMsealed classes
and method overloading. Imagine I have the following sealed class:
sealed class State {
object A : State()
data class B(val i: Int) : State()
}
And the following methods defined:
fun process(a: State.A): Unit {/**/}
fun process(b: State.B): Unit {/**/}
I should be able to call process(state)
with an instance of State
since the compiler knows that there are only two subtypes of it and that the method is defined for both of them. But it forces me to check the type (with a when
for example):
fun newState(state: State) = process(state) //doesn`t compile (None of the following functions can be called with the arguments supplied)
fun newState(state: State) = when(state) { // this works but its really verbose
is State.A -> process(state)
is State.B -> process(state)
}
streetsofboston
07/13/2019, 11:42 AMwhen
statements.
I think it can't work even with if ... else if ....
statements. And it certainly doesn't seem to work with the resolution of overloaded functions.LS
07/13/2019, 11:51 AMfun process(state: State): Unit = when (state) {
is State.A -> process(state)
is State.B -> process(state)
}
which will allow you to call process(state)LS
07/13/2019, 11:53 AMprocess
a method of State
and implementing it in each of the sealed classesEric Martori
07/13/2019, 12:35 PMLS
07/13/2019, 1:32 PMLS
07/13/2019, 1:34 PM