Yesterday I`ve asked how may I handle keyboard input (with ScalaFX) in a functional manner. Thanks to @alfilercio help I came up with something like this:
class InputHandler {
private val goUp: Int => State => State = step => state => State(state.x, state.y - step)
private val goDown: Int => State => State = step => state => State(state.x, state.y + step)
private val goLeft: Int => State => State = step => state => State(state.x - step, state.y)
private val goRight: Int => State => State = step => state => State(state.x + step, state.y)
private val doNothing: Int => State => State = step => state => state
private var behaviour: Int => State => State = doNothing
def keyPressedHandler(key: KeyEvent): Unit = {
behaviour = key.getCode match {
case KeyCode.Up.delegate => goUp
case KeyCode.Down.delegate => goDown
case KeyCode.Left.delegate => goLeft
case KeyCode.Right.delegate => goRight
case _ => doNothing
}
}
def keyReleasedHandler(key: KeyEvent): Unit = behaviour = doNothing
def update: Int => State => State = behaviour
}
Then there is an Updater (working name) thats updates state based on time passed, some internal logic and/or user input:
def update(state: State)(implicit inputHandler: InputHandler): State = { ... }
With such approach the core classes may remain pure and no single variable is needed. But there is still problem with the InputHandler itself. I mean the behaviour variable makes it statefull. This InputHandler adds kind of abstraction to ScalaFX used to generate GUI. The metdods keyPressedHandler/keyRelasedHandler are set as ScalaFX Scene events handlers respectively. To conclude, I am looking way to remove state variable (behaviour) from this InputHandler. I try to grasp functional approach for educational reasons that`s why I keep bothering you with this case :)