0__*_*0__ 6 scala pattern-matching path-dependent-type
鉴于异构类型:
trait Request {
type Result
}
trait IntRequest extends Request {
type Result = Int
}
Run Code Online (Sandbox Code Playgroud)
如何让Scala编译器满意地根据模式匹配返回路径依赖类型:
def test(in: Request): in.Result = in match {
case i: IntRequest => 1234
case _ => sys.error(s"Unsupported request $in")
}
Run Code Online (Sandbox Code Playgroud)
错误:
<console>:53: error: type mismatch;
found : Int(1234)
required: in.Result
case i: IntRequest => 1234
^
Run Code Online (Sandbox Code Playgroud)
以下作品:
trait Request {
type Result
}
final class IntRequest extends Request {
type Result = Int
}
trait Service {
def handle[Res](in: Request { type Result = Res }): Res
}
trait IntService extends Service {
def handle[Res](in: Request { type Result = Res }): Res = in match {
case i: IntRequest => 1234
case _ => sys.error(s"Unsupported request $in")
}
}
trait Test {
def service: Service
def test(in: Request): in.Result = service.handle[in.Result](in)
}
Run Code Online (Sandbox Code Playgroud)
如果使用a final class,编译器只会吃它吗?
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |