Anonymous partial function in early initializer requires “premature access to class”

妖精的绣舞 提交于 2019-12-02 03:57:54

问题


Why does this fail to compile:

trait Item

trait StringItem extends Item {
  def makeString: String
}

trait SomeOtherItem extends Item

trait DummyTrait

case class Marquee(items: Seq[Item]) extends {
  val strings: Seq[String] = items.collect {
    case si: StringItem => si.makeString   // <-- partial function inside braces
  }
} with DummyTrait

with the error message <$anon: Item => String> requires premature access to class Marquee? It seems to me that the partial function makes no use of Marquee. Yet this compiles:

val pf: PartialFunction[Item, String] = {
  case si: StringItem => si.makeString
}

case class Marquee(items: Seq[Item]) extends {
  val strings: Seq[String] = items.collect(pf)
} with DummyTrait

The first version, with the anonymous partial function inside Marquee, does compile when val strings is not an early definition (that is, if I remove with DummyTrait). I figure that's an important clue, but I haven't been able to see how DummyTrait could interfere with anything. Explicitly scoping StringItem as MyModule.StringItem so a descendant of DummyTrait can't redefine it doesn't work, either.

来源:https://stackoverflow.com/questions/27494290/anonymous-partial-function-in-early-initializer-requires-premature-access-to-cl

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