Back to Scala3

E161: Already Defined

docs/_docs/reference/error-codes/E161.md

3.8.41.6 KB
Original Source

E161: Already Defined

This error occurs when multiple definitions with the same synthesized name exist in the same scope. This commonly happens with anonymous givens that have the same type, as the compiler generates identical names for them.

When defining multiple anonymous givens of the same type, the compiler synthesizes names based on the type (e.g., given_Option_String). If two givens would have the same synthesized name, this error is reported.


Example

scala
def example = {
  given Option[String] = Some("a")
  given Option[String] = Some("b")
  ()
}

Error

scala
-- [E161] Naming Error: example.scala:3:8 --------------------------------------
3 |  given Option[String] = Some("b")
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |given_Option_String is already defined as given instance given_Option_String
  |
  |Provide an explicit, unique name to given definitions,
  |since the names assigned to anonymous givens may clash. For example:
  |
  |      given myGiven: Option[String]  // define an instance
  |      given myGiven @ Option[String] // as a pattern variable

Solution

scala
def example = {
  // Provide explicit unique names for givens
  given first: Option[String] = Some("a")
  given second: Option[String] = Some("b")
  ()
}
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>