Anonymous partial function in early initializer requires "premature access to class"
Asked Answered
S

0

2

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.

Spoof answered 15/12, 2014 at 22:24 Comment(5)
Anonymous classes have access to their enclosing class. The compiler doesn't know that your anonymous partial function doesn't actually access anything (and it would be very hard to check this in full generality); it simply disallows creating any anonymous classes until you're into the class proper.Eleen
@Imm Where is the (offending) anonymous class? The error message complains about an anonymous function, not an anonymous class. This compiles: val pairs: Seq[(Item, Item)] = items.map { item => (item, item) }, so I figure the restriction is indeed not against anonymous functions.Spoof
Hmm. Maybe it's the PartialFunction? If you do val collector: PartialFunction[Item, String] = {case si: StringItem => si.makeString} is that disallowed?Eleen
@Imm Just tried it. That line fails, with the same error message from the compiler.Spoof
Someone linked the ticket at #30823881 which duplicates this.Dani

© 2022 - 2024 — McMap. All rights reserved.