Anonymous partial function in early initializer re

2020-04-15 05: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.

0条回答
登录 后发表回答