E049: Ambiguous Reference

This error is emitted when an identifier could refer to multiple different definitions and the compiler cannot determine which one to use.

The precedence of the different kinds of name bindings, from highest to lowest, is:

  1. Definitions in an enclosing scope
  2. Inherited definitions and top-level definitions in packages
  3. Names introduced by import of a specific name
  4. Names introduced by wildcard import
  5. Definitions from packages in other files

Note that definitions take precedence over imports, and a binding in an inner scope cannot shadow a binding with higher precedence in an outer scope.


Example

import scala.collection.immutable.Seq
import scala.collection.mutable.Seq

val items = Seq(1, 2, 3)

Error

-- [E049] Reference Error: example.scala:4:12 ----------------------------------
4 |val items = Seq(1, 2, 3)
  |            ^^^
  |  Reference to Seq is ambiguous.
  |  It is both imported by name by import scala.collection.immutable.Seq
  |  and imported by name subsequently by import scala.collection.mutable.Seq
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The identifier Seq is ambiguous because two name bindings of equal precedence
  | were introduced in the same scope.
  |
  | The precedence of the different kinds of name bindings, from highest to lowest, is:
  |  - Definitions in an enclosing scope
  |  - Inherited definitions and top-level definitions in packages
  |  - Names introduced by import of a specific name
  |  - Names introduced by wildcard import
  |  - Definitions from packages in other files
  | Note:
  |  - As a rule, definitions take precedence over imports.
  |  - Definitions in an enclosing scope take precedence over inherited definitions,
  |    which can result in ambiguities in nested classes.
  |  - When importing, you can avoid naming conflicts by renaming:
  |    import scala.{Seq => SeqTick}
   -----------------------------------------------------------------------------

Solution

// Use a rename to avoid the conflict
import scala.collection.immutable.Seq
import scala.collection.mutable.{Seq as MutableSeq}

val items = Seq(1, 2, 3)
val mutableItems = MutableSeq(1, 2, 3)
import scala.collection.{immutable, mutable}
// Or use qualified names
val items = immutable.Seq(1, 2, 3)
val mutableItems = mutable.Seq(1, 2, 3)
// Or import only what you need
import scala.collection.immutable.Seq

val items = Seq(1, 2, 3)