Skip to content

Async code access to a variable in App fails in Dotty #16149

Open
@mkotsur

Description

@mkotsur

Compiler version

3.2.0

Minimized code

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

object MapTest extends App {
  import concurrent.ExecutionContext.Implicits.global

  val test = "123"

  val dataF = Future { List("111", "222", "333", test) }

  Await.ready(dataF, 1.second)
}

Output

Exception in thread "main" java.lang.ExceptionInInitializerError
	at MapTest.main(MapTest.scala)
Caused by: java.util.concurrent.TimeoutException: Future timed out after [1 second]
	at scala.concurrent.impl.Promise$DefaultPromise.tryAwait0(Promise.scala:248)
	at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:255)
	at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:104)
	at scala.concurrent.Await$.$anonfun$ready$1(package.scala:174)
	at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:62)
	at scala.concurrent.Await$.ready(package.scala:124)
	at MapTest$.<clinit>(MapTest.scala:13)
	... 1 more
java.lang.NoClassDefFoundError: Could not initialize class MapTest$

Expectation

I'm aware of the intricacies of DelayedInit and App. However, since this works in Scala 2.13, I would expect this to also work in Scala 3 because the doc hasn't change: doc dotty, doc 2.13.3.

Moreover, looking at this statement:

It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

it's not clear why wrapping code into a Future makes any difference. Isn't access to test on line 3 happening before the method has been executed? 🤔

object PrintTest extends App {
  val test = "123"
  println(test)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions