Skip to content

Initialisation Exception #15832

Open
Open
@Arthurm1

Description

@Arthurm1

Compiler version

3.1.3 and 3.2.0-RC1 on Scastie

Minimized code

object A {
  class Builder[K, V](creator: K => V) {
    def build(k: K): V = creator(k)
  }
  case class Foo(id: Int) extends AnyVal
  object Foo extends Builder[Int, Foo](k => new Foo(k)) {
    def apply(str: String): Foo = str match {
      case "Foo1" => foo1
    }
  }
  val foo1: Foo = Foo.build(1)
}

object B {
  val foo = A.Foo.apply("Foo1")
}

B.foo

Output

java.lang.ExceptionInInitializerError
	at Playground$A$Foo$.<init>(main.scala:8)
	at Playground$A$Foo$.<clinit>(main.scala:8)
	at Playground$B$.<clinit>(main.scala:17)
	at Playground$.<clinit>(main.scala:20)
	at Main$.<clinit>(main.scala:24)
	at Main.main(main.scala)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at sbt.Run.invokeMain(Run.scala:143)
	at sbt.Run.execute$1(Run.scala:93)
	at sbt.Run.$anonfun$runWithLoader$5(Run.scala:120)
	at sbt.Run$.executeSuccess(Run.scala:186)
	at sbt.Run.runWithLoader(Run.scala:120)
	at sbt.Run.run(Run.scala:127)
	at com.olegych.scastie.sbtscastie.SbtScastiePlugin$$anon$1.$anonfun$run$1(SbtScastiePlugin.scala:38)
	at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
	at sbt.util.InterfaceUtil$$anon$1.get(InterfaceUtil.scala:17)
	at sbt.ScastieTrapExit$App.run(ScastieTrapExit.scala:259)
	at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.NullPointerException: Cannot invoke "Playground$A$Foo$.build(Object)" because "Playground$A$Foo$.MODULE$" is null
	at Playground$A$.<clinit>(main.scala:13)
	... 21 more

Expectation

My initialisation ordering might be dubious but this works in Scala 2.

Works if I change val foo1 to lazy val foo1 or if I put all the code intoobject A

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions