【问题标题】:Pattern matching refuses to recognize member type (value X is not a member of _2)模式匹配拒绝识别成员类型(值 X 不是 _2 的成员)
【发布时间】:2013-05-05 22:06:10
【问题描述】:

在以下情况下,Scala 似乎不承认 system 的类型:

sealed trait Bar[S] {
  def system: S
}

trait Foo { def bar(): Unit }

trait FooBar extends Bar[Foo]

如果我没有完全困惑,这意味着我应该能够做到以下几点:

def test(fb: FooBar) { fb.system.bar() }  // ok, this works

但以下失败:

trait Test[S] {
  val bar: Bar[S]

  bar match {
    case fb: FooBar => fb.system.bar() // error: value bar is not a member of _2
    case _ =>
  }
}

这是模式匹配器中的一个错误,还是我遗漏了一个关键点?


编辑:注意,以下工作:

trait Test[S] {
  val bar: Bar[S]

  bar match {
    case fb: FooBar => (fb: FooBar).system.bar()
    case _ =>
  }
}

我想我应该提交一个错误?

【问题讨论】:

    标签: scala types pattern-matching


    【解决方案1】:

    这里肯定涉及类型擦除,但我不能 100% 确定您看到的是错误或预期行为。因为您将bar val 声明为Bar[S],所以S 被删除并且模式匹配器没有可使用的基础类型。您可以通过将匹配更改为:

    case fb:Bar[Foo] =>
    

    奇怪的是,如果您将 bar 声明为 Any 类型,您的原始匹配将起作用。此外,如果您将鼠标悬停在匹配语句中的 fb 上,您可以看到它被视为:

    Bar[S] with FooBar
    

    再次,我相信这一切都可以追溯到bar 的声明方式。虽然不确定这是一个错误,但我想对模式匹配器的内部工作有更多经验的人可能会有更深入的解释。

    【讨论】:

    • FooBar是平面类型,所以擦除没有问题。另请注意,编译器接受我的类型注释(fb: FooBar),因此匹配案例发出的类型肯定有些奇怪。
    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多