val initialized from a val/var defined later in the same block
ID |
scala.correctness.forward_reference |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Initialization |
Language |
Scala |
Description
Reports a val whose initializer reads another val or var that is only defined further down the same block.
Rationale
Scala does not reject the forward reference; it evaluates the initializer before the later definition has run, so the value read is the field’s default — null for a reference, 0 for a numeric — and the first symptom is usually a NullPointerException far from this line, or a silently wrong constant. Reordering the two statements, which looks like a cosmetic change, also changes the result, so the defect survives refactoring and reappears.
The following code illustrates the pattern detected by this rule:
object Settings {
def resolve(): String = {
// FLAGGED: val initialized from a val/var defined later in the same block
val effective = fallback
val fallback = "default"
effective
}
}