Type inheritance misunderstanding in Request Respo

2019-08-01 10:06发布

问题:

I am trying to make a small messaging system with scala. I can`t figure out how to solve this class/type/generics/hierarchy problem on line with //PROBLEM

The logic is: Request has a list of functions to invoke with the response when arrives. When Response arrives getResult is invoked and pattern matching is used. It seems that I cannot invoke the functions from list on Request which can be overloaded by any subtype of Response ?

object Worksheet {
    class Request {
        //var op = List[( _<:Response ) => Unit]()
        var op = List[Response => Unit]()             // FIXED
    }
    class Response {}
    class MyResult extends Response {}
    class AnotherMyResult extends Response {}

    val map = Map[String, Request]()                  

  def getResult(a:Any) {
    a match {
            ...
        case r:Response =>
            //map.get("").get.op foreach ((o) => o(r)) //PROBLEM 
                      map("").op foreach ((o) => o(r))        //NO PROBLEM 
            ...
    }
  }                                               
}

Please help ;)

EDIT

  def simpleop (r:MyResult) : Unit = { }

  def req = new Request()
  req.op += simpleop _                      //PROBLEM STILL

  map += ("" -> req)

回答1:

You can't call method simpleop with parameter of type Response, so you can't have both: case r:Response => map("").op foreach ((o) => o(r)) and req.op += simpleop _.