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

时间:2014-07-16 16:50:14

标签: 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 request $in")
}

错误:

<console>:53: error: type mismatch;
 found   : Int(1234)
 required: in.Result
         case i: IntRequest => 1234
                               ^

2 个答案:

答案 0 :(得分:6)

以下作品:

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

如果使用final class,编译器只会吃掉它!!

答案 1 :(得分:0)

我认为最好使用类型类而不是需要覆盖的依赖类型模式匹配,所以在这种情况下,我们不需要在参数内重新定义Request。

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
相关问题