在我的应用程序中,我有一组封闭的操作,它们返回对应的一组响应,如下所示。
sealed trait OperationCompletionResponse {
val state: Int
}
case class ExecutionStartedResponse(state: Int) extends OperationCompletionResponse
case class UpdateRecordedResponse(state: Int) extends OperationCompletionResponse
case class ExecutionTerminatedResponse(state: Int) extends OperationCompletionResponse
sealed trait Operation {
type R
def createResponse(state: Int): R
}
case class StartExecutionOperation() extends Operation {
type R = ExecutionStartedResponse
override def createResponse(state: Int): ExecutionStartedResponse = ExecutionStartedResponse(state)
}
case class RecordUpdateOperation() extends Operation {
type R = UpdateRecordedResponse
override def createResponse(state: Int): UpdateRecordedResponse = UpdateRecordedResponse(state)
}
case class TerminateExecutionOperation() extends Operation {
type R = ExecutionTerminatedResponse
override def createResponse(state: Int): ExecutionTerminatedResponse = ExecutionTerminatedResponse(state)
}
就我对类型成员和类型投影的理解而言,我可以执行以下操作。根据scala编译器
,它们是完全有效的语句val esr:StartExecutionOperation#R = ExecutionStartedResponse(1)
val teo:TerminateExecutionOperation#R = ExecutionTerminatedResponse(-1)
val ruo:RecordUpdateOperation#R = UpdateRecordedResponse(0)
但是,我现在想在一个函数中使用它们;这通常更有用。现在,如何将输出类型指定为从属类型?
def updateState[O <: Operation](operation: O) = operation match {
case StartExecutionOperation() => ExecutionStartedResponse(1)
case TerminateExecutionOperation() => ExecutionTerminatedResponse(-1)
case RecordUpdateOperation() => UpdateRecordedResponse(0)
}
更具体地说,我不希望函数的返回类型为 OperationCompletionResponse ,而是类似 Operation#R 或 operation.R < / strong>
我该怎么做?
答案 0 :(得分:2)
与路径有关的类型updateState
将直接链接到operation
的类型。您不想在正文中匹配operation
,因为它永远不会为您提供您要查找的R
类型。
您恰好定义了一个操作R
,即createResponse
。由于createResponse
需要一个整数参数,因此您必须以某种方式在updateState
中给它。似乎每个操作都有一些默认状态,因此可以定义def defaultState: Int
Operation
然后具有
def updateState(op: Operation): op.R = op.createResponse(op.defaultState)`
如果这不能回答您的问题,请对其进行编辑,以更具体地说明您在此状态下要实现的目标。