不能将 PartialFunction 放在 Scala 类构造函数中 [英] Can't put PartialFunction in scala class constructor

查看:79
本文介绍了不能将 PartialFunction 放在 Scala 类构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There appears to be a restriction that you 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 => Any> requires premature access to class X.
   case class X(a: PartialFunction[Any, Any]) { def this() = this({ case x => x}) }

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

My first question is why does a partial function literal need access to "this". My second question/observation is that in the Scala REPL, running the same code again crashes the 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)
    ...

最后,这个问题有没有好的解决方法?

And lastly, is there a good workaround for this issue?

推荐答案

你的第一个问题得到解答 在这个问题的评论部分

Your first question is answered in the comment section of this question

引用 Imm:

匿名类可以访问它们的封闭类.编译器不知道您的匿名部分函数实际上没有访问任何内容(并且很难全面检查这一点);它只是禁止创建任何匿名类,直到您进入正确的类.

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.

为什么它会导致 REPL 崩溃是一个很好的问题,您可能应该使用此代码示例向 Typesafe 提交一张票.

Why it crashes the REPL is a good question, you should probably submit a ticket to Typesafe with this code example.

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

A workaround is quite simple, just define the anonymous function outside of the class so the compiler knows the exact state you are closing over:

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

case class X(a: PartialFunction[Any, Any]) {
  def this() = this(X.Default)
}

这篇关于不能将 PartialFunction 放在 Scala 类构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆