Wildcard import hides the origin of the names it brings in
ID |
scala.maintainability.avoid_star_import |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Readability |
Language |
Scala |
Description
Reports a wildcard import (import pkg._, spelled import pkg.* in Scala 3), which brings every public member of a package or object into scope instead of naming what is used.
Rationale
A wildcard import makes it impossible to tell, from the top of the file, where a given name comes from - the reader has to search. It also makes the file fragile against changes it does not control: a new member added to the imported package can shadow a name already in scope, or make a call ambiguous, and the code breaks without anyone having touched it. Wildcards over implicit-bearing objects additionally pull in implicits the author never considered.
The following code illustrates the pattern detected by this rule:
// FLAGGED: Wildcard import hides the origin of the names it brings in
import scala.collection.mutable._
Remediation
Import only what the file uses, either as individual imports or with a selector list - import scala.collection.mutable.{ArrayBuffer, ListBuffer}. Keep the wildcard for the established idioms that need it, such as importing a package object’s implicits or the members of a DSL, and put such imports in the narrowest scope that works rather than at file level.