首页 > 解决方案 > 初始化顺序在惰性 val 访问时抛出空指针

问题描述

预期,以下没有惰性 val 的初始化顺序会引发空指针异常

class Foo {
  Bar.x // NullPointerException
}

object Bar extends Foo {
  val x = 42
}

object Hello extends App {
  Bar
}

检查-Xprint:jvm输出并引用@paradigmatic answer,我们看到这是由于' 的构造函数首先运行并且在 ' 的构造函数中初始化之前Foo调用:Bar.x()Bar.this.xBar

  class Foo extends Object {
    def <init>(): example.Foo = {
      Foo.super.<init>();
      Bar.x();
      ()
    }
  };

  object Bar extends example.Foo {
    private[this] val x: Int = _;
    <stable> <accessor> def x(): Int = Bar.this.x;
    def <init>(): example.Bar.type = {
      Bar.super.<init>();
      Bar.this.x = 42;
      ()
    }
  };

但是,为什么像这样惰性x时也会抛出空指针

object Bar extends Foo {
  lazy val x = 42
}

在惰性情况下分析-Xprint:jvm输出,我们有

  class Foo extends Object {
    def <init>(): example.Foo = {
      Foo.super.<init>();
      Bar.x();
      ()
    }
  };
  object Bar extends example.Foo {
    final <synthetic> lazy private[this] var x: Int = _;
    @volatile private[this] var bitmap$0: Boolean = _;
    private def x$lzycompute(): Int = {
      Bar.this.synchronized(if (Bar.this.bitmap$0.unary_!())
        {
          Bar.this.x = (42: Int);
          Bar.this.bitmap$0 = true
        });
      Bar.this.x
    };
    <stable> <accessor> lazy def x(): Int = if (Bar.this.bitmap$0.unary_!())
      Bar.this.x$lzycompute()
    else
      Bar.this.x;
    def <init>(): example.Bar.type = {
      Bar.super.<init>();
      ()
    }
  };

在我看来,由于bitmap$0警卫,它应该可以工作

    <stable> <accessor> lazy def x(): Int = if (Bar.this.bitmap$0.unary_!())
      Bar.this.x$lzycompute()
    else
      Bar.this.x;

运行时字段访问器检查-Xcheckinit似乎在我的机器上使用 Scala 2.12.8 很满意,那么为什么是NullPointerException什么时候lazy val x呢?

标签: scalainitializationlazy-evaluation

解决方案


我认为这个 NPE 根本不相关val。检查这个:

class Foo {
  Bar.anyMethod
}

object Bar extends Foo {
  def anyMethod = ???
}

object Hello extends App {
  Bar
}

//java.lang.NullPointerException

Foo正在尝试在仍在建设中Bar时运行构造函数。Bar所以这也是你Foo在打电话之前正在做的事情x

顺便说一句,如果您将所有内容都放入Hellowithmain方法中,那么在我和您的情况下,您将获得 StackOverflow 而不是 NPE。

object Hello {

   def main(args: Array[String]): Unit = {

     class Foo {
       Bar.anyMethod
     }

     object Bar extends Foo { //<- Bar is like local val now instead of field 
       def anyMethod= ???     // of package object, so stack is available now.
     }

     Bar
   }

}

推荐阅读