Can't put PartialFunction in scala class constructor -
there appears restriction can't use partialfunction
literals in class constructors:
scala> case class x(a: partialfunction[any, any]) { def this() = this({case x => x}) } <console>:7: error: implementation restriction: <$anon: => any> requires premature access class x. case class x(a: partialfunction[any, any]) { def this() = this({ case x => x}) }
my first question why partial function literal need access "this". second question/observation in scala repl, running same code again crashes repl:
scala> case class x(a: partialfunction[any, any]) { def this() = this({ case x => x}) } java.lang.nullpointerexception @ scala.tools.nsc.global$run.compilelate(global.scala:1595) @ scala.tools.nsc.globalsymbolloaders.compilelate(globalsymbolloaders.scala:29) @ scala.tools.nsc.symtab.symbolloaders$sourcefileloader.docomplete(symbolloaders.scala:369) ...
and lastly, there workaround issue?
your first question answered in comment section of question
quoting imm:
anonymous classes have access enclosing class. compiler doesn't know anonymous partial function doesn't access (and hard check in full generality); disallows creating anonymous classes until you're class proper.
why crashes repl question, should submit ticket typesafe code example.
a workaround quite simple, define anonymous function outside of class compiler knows exact state closing over:
object x { val default: partialfunction[any, any] = { case x => x } } case class x(a: partialfunction[any, any]) { def this() = this(x.default) }
Comments
Post a Comment