【问题标题】:Referring to a the sub-type of a path-dependent type引用路径依赖类型的子类型
【发布时间】:2016-06-03 05:48:42
【问题描述】:

以下作品:

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

但这仅仅是因为Inner 的所有子类型都有一个明确的type 成员。是否可以从路径相关类型的子类型构造一个值,而 不需要在 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 (?)

【问题讨论】:

    标签: scala path-dependent-type


    【解决方案1】:
    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
    

    【讨论】:

    • "这是一个类型别名。Either[Int, String] 不是Either 的子类"是的,我知道。那不是我的问题(顺便说一下,Either[Int,String]Either 不同。前者是正确的类型,后者是arity 2 的类型构造函数)。
    • 问题是,我如何创建预期类型的​​LeftRight(即o.Innernot Inner)。我手边没有 REPL,但我认为您的代码没有类型检查(类型不匹配,需要 o.Inner,找到 Left
    • "顺便说一句,Either[Int,String]Either 不一样"。这是我的一个错字。我的意思是说“Inner 不是Either[Int, String] 的子类”。我编辑了我的答案。
    • 显然你是对的!我会尝试一下,然后我会回来
    • 请看相关问题(我在这个末尾添加了)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2023-03-05
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多