Field declared in an object extending App (DelayedInit)

ID

scala.correctness.delayed_init_field

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

low

Resource

Initialization

Language

Scala

Description

Reports a val or var declared in the body of an object that extends App, whose initialization App defers through the DelayedInit mechanism.

Rationale

App moves the whole object body into a thunk that runs from main, so the fields are not initialized when the object is constructed. Anything that touches them earlier — another object’s initializer, a static forwarder, a framework reflecting over the class, or a thread started from the body — reads null or zero. The same deferral makes the fields unreliable under -Xcheckinit and breaks if the object is used as a library entry point rather than run directly. DelayedInit has been deprecated since Scala 2.11 and App is not recommended in Scala 3.

The following code illustrates the pattern detected by this rule:

// FLAGGED: Field declared in an object extending App (DelayedInit)
object Importer extends App {
  val inputPath: String = args(0)
  println(s"importing from $inputPath")
}

Remediation

Write the entry point explicitly: object Importer { def main(args: Array[String]): Unit = { …​ } }, with the values as local val`s inside `main. Where the object must stay an App, make the fields lazy val so each is computed on first access.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved