加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:58:08 所属栏目:安全 来源:网络整理
导读:似乎存在一个限制,即您不能在类构造函数中使用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
似乎存在一个限制,即您不能在类构造函数中使用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}) }

我的第一个问题是为什么部分函数文字需要访问“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)
    ...

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

解决方法

你的第一个问题是 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的票证.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读