为这个菜鸟问题道歉,但我对 Scala 很陌生。
我有以下 Scala 类:
class Test {
class Request {def getValue(): String = {"request"}}
class Response {def getValue(): String = {"response"}}
case class MyRequest(message: String) extends Request
case class MyResponse(message: String) extends Response
val myFunction: (Request) => Response = doSomething
private val functions = scala.collection.mutable.Map[String, (Request) => Response](
"myFunction" -> myFunction
)
def doSomething(request: MyRequest): MyResponse = {
null
}
}
无法编译并出现以下错误:
type mismatch;
found : Test.this.MyRequest => Test.this.MyResponse
required: Test.this.Request => Test.this.Response
val myFunction: (Request) => Response = doSomething
如果我将 myFunction 和函数的声明更改为:
val myFunction: (MyRequest) => MyResponse = doSomething
private val functions = scala.collection.mutable.Map[String, (MyRequest) => MyResponse](
"myFunction" -> myFunction
)
但这不是我想要的——我希望能够将具有不同具体类型(都扩展请求或响应)的其他功能添加到地图中。因此,我想将地图声明为采用请求或响应的任何子类。
知道我在这里做错了什么吗?