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

爷,独闯天下 提交于 2019-12-11 11:20:53

问题


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


来源:https://stackoverflow.com/questions/35542846/referring-to-a-the-sub-type-of-a-path-dependent-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!