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

scala – 在抽象构造函数中访问overriden val时出现NullPointerE

发布时间:2020-12-16 18:50:49 所属栏目:安全 来源:网络整理
导读:考虑以下(简化)示例: abstract class Bar[T] { val f: PartialFunction[T,T] val default: PartialFunction[T,T] = { case x = x } val chained = f orElse default}class Foo extends Bar[Int] { val f: PartialFunction[Int,Int] = { case 1 = 2 }} 看着
考虑以下(简化)示例:

abstract class Bar[T] {
    val f: PartialFunction[T,T]
    val default: PartialFunction[T,T] = { case x => x }
    val chained = f orElse default
}

class Foo extends Bar[Int] {
    val f: PartialFunction[Int,Int] = { case 1 => 2 }
}

看着它崩溃:

scala> val foo = new Foo
java.lang.NullPointerException
        at Bar.<init>(<console>:8)
        at Foo.<init>(<console>:6)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at RequestResult$.<init>(<console>:9)
        at RequestResult$.<clinit>(<console>)
        at RequestResult$scala_repl_result(<console>)
        ....

但是,如果我们将链接放在具体类中:

abstract class Bar[T] {
    val f: PartialFunction[T,T] = { case x => x }
}

class Foo extends Bar[Int] {
    val f: PartialFunction[Int,Int] = { case 1 => 2 }
    val chained = f orElse default
}

它按预期工作:

scala> val foo = new Foo
foo: Foo = Foo@16132c4

我不得不承认我完全不知道这里发生了什么.错误? (这是在Scala 2.8.1上.)

解决方法

“为什么我的抽象或覆盖val为空?” https://github.com/paulp/scala-faq/wiki/Initialization-Order

(编辑:李大同)

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

    推荐文章
      热点阅读