Unexplained numeric literal

ID

scala.maintainability.magic_number

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Numeric Literal

Language

Scala

Description

Reports a numeric literal of three or more digits used directly as the initialiser of a val or var, where nothing names what the number means. Constants declared with final val are excluded, as are the round scale factors 100, 1000, 10000, 100000, 1000000 and 1024.

Rationale

A bare number carries no unit and no reason. A reader meeting 86400 has to work out that it is a day in seconds, and cannot tell whether the 86400 three files away is the same quantity or a coincidence - so when the value has to change, some occurrences get updated and others do not. Naming it once turns that guesswork into a definition and makes every use consistent by construction.

The following code illustrates the pattern detected by this rule:

class MagicNumber {
  // FLAGGED: Unexplained numeric literal
  val cacheTtl = 86400
}

Remediation

Extract the literal into a named constant whose name states the quantity and its unit, for example final val SecondsPerDay = 86400, and use the name at each site. Where the value is a duration or a size, prefer a typed representation - scala.concurrent.duration.DurationInt gives 1.day, which carries the unit in the type.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved