无法将PartialFunction放在scala类构造函数中

Yon*_*ree 6 scala partialfunction

似乎有一个限制,你不能PartialFunction在类构造函数中使用文字:

scala> case class X(a: PartialFunction[Any, Any]) { def this() = this({case x => x}) }
<console>:7: error: Implementation restriction: <$anon: Any => Any> requires premature access to class X.
   case class X(a: PartialFunction[Any, Any]) { def this() = this({ case x => x}) }
Run Code Online (Sandbox Code Playgroud)

我的第一个问题是为什么部分函数文字需要访问"this".我的第二个问题/观察是在Scala REPL中,再次运行相同的代码会导致REPL崩溃:

scala> case class X(a: PartialFunction[Any, Any]) { def this() = this({ case x => x}) }
java.lang.NullPointerException
    at scala.tools.nsc.Global$Run.compileLate(Global.scala:1595)
    at scala.tools.nsc.GlobalSymbolLoaders.compileLate(GlobalSymbolLoaders.scala:29)
    at scala.tools.nsc.symtab.SymbolLoaders$SourcefileLoader.doComplete(SymbolLoaders.scala:369)
    ...
Run Code Online (Sandbox Code Playgroud)

最后,这个问题有一个很好的解决方法吗?

Ako*_*chy 7

您的第一个问题在此问题的评论部分得到了解答

引用Imm:

匿名类可以访问其封闭类.编译器不知道你的匿名部分函数实际上没有访问任何东西(并且很难完全检查这一点); 它只是不允许创建任何匿名类,直到你进入正确的类.

为什么它崩溃REPL是一个很好的问题,您应该使用此代码示例提交一个Typesafe的票证.

解决方法非常简单,只需在类外部定义匿名函数,以便编译器知道您要关闭的确切状态:

object X {
  val Default: PartialFunction[Any, Any] = { case x => x }
}

case class X(a: PartialFunction[Any, Any]) {
  def this() = this(X.Default)
}
Run Code Online (Sandbox Code Playgroud)