简体   繁体   English

模式匹配拒绝识别成员类型(值X不是_2的成员)

[英]Pattern matching refuses to recognize member type (value X is not a member of _2)

In the following situation Scala seems to not acknowledge the type of system : 在以下情况下,Scala似乎不承认system的类型:

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

trait Foo { def bar(): Unit }

trait FooBar extends Bar[Foo]

If I'm not completely confused, this means that I should be able to do the following: 如果我不完全困惑,这意味着我应该能够执行以下操作:

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

But the following fails: 但是以下失败:

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 _ =>
  }
}

Is this a bug in the pattern matcher, or am I missing a crucial bit? 这是模式匹配器中的错误,还是我缺少关键的一点?


EDIT : Note, the following works: 编辑 :请注意,以下工作:

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

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

I guess I should file a bug? 我想我应该提交一个错误?

Type erasure is definitely involved here, but I'm not 100% sure that what you are seeing is a bug or expected behavior. 这里肯定涉及类型擦除,但是我不确定100%确定您看到的是错误或预期的行为。 Because you declare the bar val as Bar[S] , S gets erased and the pattern matcher does not have the underlying type to work with. 因为您将bar val声明为Bar[S] ,所以S被擦除,并且模式匹配器没有基础类型可以使用。 You can see the erasure warning by changing your match to: 您可以通过将匹配项更改为以下内容来查看删除警告:

case fb:Bar[Foo] =>

The odd thing is that if you declared bar as type Any your original match would work. 奇怪的是,如果您将bar声明为Any类型,则原始匹配将起作用。 Also, if you hover over fb in your match statement, you can see that it's being treated as: 另外,如果将鼠标悬停在match语句中的fb上,则可以看到它被视为:

Bar[S] with FooBar

Again, I believe this all goes back to how bar is being declared. 同样,我相信所有这些都可以追溯到如何声明bar Not sure this is a bug though and I imagine someone with more experience in the inner workings of the pattern matcher might have a more in depth explanation. 不过,不确定这是否是一个错误,我想如果有人对模式匹配器的内部工作有更多的经验,可能会有更深入的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM