How to call the correct method in Scala/Java based the types of two objects without using a switch statement?

前端 未结 5 1157
星月不相逢
星月不相逢 2020-12-28 22:28

I am currently developing a game in Scala where I have a number of entities (e.g. GunBattery, Squadron, EnemyShip, EnemyFighter) that all inherit from a GameEntity class. Ga

5条回答
  •  太阳男子
    2020-12-28 22:44

    You can easily implement multiple dispatch in Scala, although it doesn't have first-class support. With the simple implementation below, you can encode your example as follows:

    object Receive extends MultiMethod[(Entity, Message), String]("")
    
    Receive defImpl { case (_: Fighter, _: Explosion) => "fighter handling explosion message" }
    Receive defImpl { case (_: PlayerShip, _: HullBreach) => "player ship handling hull breach" }
    

    You can use your multi-method like any other function:

    Receive(fighter, explosion) // returns "fighter handling explosion message"
    

    Note that each multi-method implementation (i.e. defImpl call) must be contained in a top-level definition (a class/object/trait body), and it's up to you to ensure that the relevant defImpl calls occur before the method is used. This implementation has lots of other limitations and shortcomings, but I'll leave those as an exercise for the reader.

    Implementation:

    class MultiMethod[A, R](default: => R) {
      private var handlers: List[PartialFunction[A, R]] = Nil
    
      def apply(args: A): R = {
        handlers find {
          _.isDefinedAt(args)
        } map {
          _.apply(args)
        } getOrElse default
      }
    
      def defImpl(handler: PartialFunction[A, R]) = {
        handlers +:= handler
      }
    }
    

提交回复
热议问题