参考路径依赖类型的子类型

时间:2016-02-21 22:18:16

标签: scala path-dependent-type

以下作品:

class Outter {
    type Inner = Either[Int,String]
    type L = Left[Int,String]
    type R = Right[Int,String]

    def f(x: Inner) = 1
  }

  val o = new Outter
  o.f(new o.L(1))
  o.f(new o.R("name"))

但仅仅因为type的所有子类型都有明确的Inner成员。是否可以从路径依赖类型的子类型构造一个值而不需要Outter中明确提及它们?像:

class Outter {
    type Inner = Either[Int,String]
    def f(x: Inner) = 1
  }

  val o = new Outter
  o.f(new o.?!?(1))  // How do I express "that particular Left[Int,String] which is the sub-type of o.Inner
  o.f(new o.?!?("name")) // same as above here, but for Right

相关Path-dependent argument type is not enforced (?)

1 个答案:

答案 0 :(得分:2)

type Inner = Either[Int, String]

这是一个类型别名。 Inner不是Either[Int, String]的子类,它们是相同的。只是语法糖。 所以你可以引用Either[Int, String]的子类,好像它们是Inner

的子类

因此,解决方案可能比您想象的更直接。

val o = new Outter
o.f(Left(1)) // How do I express "that particular Left[Int,String] which is the sub-type of o.Inner
o.f(Right("name")) // same as above here, but for Right