https://kotlinlang.org logo
Title
g

gabrielfv

01/24/2020, 6:29 PM
Given you have an API for an specific situation that is supposed to be used somewhat like that:
interface StateMachine<S> {
    fun updateState(state: S)
}
Where
S
needs to be a class that is able to represent the state of an UI element. What would you set as the upper-bound of
S
?
// 1
interface StateMachine<S : Any>
or
// 2
interface StateMachine<S : State>

// where
interface State  // There is no specific contract expected
1️⃣ 1
2️⃣ 7
c

Czar

01/28/2020, 5:34 PM
I would also make
State
a sealed class instead of an interface, if possible. In fact why not make the
StateMachine
itself a sealed class hierarchy and get rid of the generic parameter altogether? E.g.
sealed class Door
class OpenDoor : Door()
class ClosedDoor : Door()
// instead of
interface DoorState
class Closed : DoorState
class Open : DoorState
class Door<DoorState>

//this would make use of the state machine more type safe, and no dealing with type erasure.
g

gabrielfv

01/28/2020, 5:42 PM
Because that's completely off the point. Something I forgot to mention,
StateMachine
is an API to be implemented in multiple different contexts (thus why it's an
interface
, not a
class
). So the concrete usage would be something like you mentioned:
class MyStateMachine : StateMachine<Door> {
    // ...
}

sealed class Door [: State] {
    class OpenDoor : Door()
}
c

Czar

01/28/2020, 5:59 PM
I see, that's why I have "if possible" in my answer, not knowing the full context I was just making a generic suggestion 🙂