Referring to a the sub-type of a path-dependent ty

2019-08-09 16:28发布

问题:

The following works:

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

but only because there is an explicit type member for all the sub-types of the Inner. Is it possible to construct a value from a sub-type of a path-dependent type without the need to mention them explicitly in the Outter ? Like:

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

Related Path-dependent argument type is not enforced (?)

回答1:

type Inner = Either[Int, String]

This is a type alias. Inner is not a subclass of Either[Int, String] they are the same. Just syntactic sugar. So you can stil refer to the subclasses of Either[Int, String] as if they are subclasses of Inner

So the solution might be more straightforward then you imagined.

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