Scala 从模式匹配返回路径相关类型

Scala 从模式匹配返回路径相关类型,scala,pattern-matching,path-dependent-type,Scala,Pattern Matching,Path Dependent Type,给定异构类型: trait Request { type Result } trait IntRequest extends Request { type Result = Int } 如何使Scala编译器满意地返回基于模式匹配的路径依赖类型: def test(in: Request): in.Result = in match { case i: IntRequest => 1234 case _ => sys.error(s"Unsupported req

给定异构类型:

trait Request {
  type Result
}

trait IntRequest extends Request {
  type Result = Int
}
如何使Scala编译器满意地返回基于模式匹配的路径依赖类型:

def test(in: Request): in.Result = in match {
  case i: IntRequest => 1234
  case _ => sys.error(s"Unsupported request $in")
}
错误:

<console>:53: error: type mismatch;
 found   : Int(1234)
 required: in.Result
         case i: IntRequest => 1234
                               ^
:53:错误:类型不匹配;
发现:Int(1234)
必填项:in.Result
案例一:IntRequest=>1234
^
以下工作:

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)
}

但是,编译器只有在使用
最终类时才会吃掉它

我认为最好使用类型类,而不是需要重写的依赖类型模式匹配,因此在这种情况下,我们不需要在参数中重新定义请求

trait Request[T] {
  type Result = T
}

trait IntRequest extends Request[Int] {
}

def test[T](in: Request[T]): T = in match {
  case i: IntRequest => 123
  case _ => sys.error(s"Unsupported request $in")
}

test(new IntRequest {}) // 123

test(new Request[String] {}) // error

是的,那是有可能的。但是,我将它们存储在
映射中,因此从编译器的角度来看,类型参数丢失了。这就是为什么我喜欢在这里使用类型成员。