Back to Scala3

E051: Ambiguous Overload

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

3.8.42.4 KB
Original Source

E051: Ambiguous Overload

This error is emitted when there are multiple overloaded methods that match the given arguments and the compiler cannot determine which one to call.

There are multiple methods that could be referenced because the compiler knows too little about the expected type. You may specify the expected type by:

  • Assigning the result to a value with a specified type
  • Adding a type ascription as in instance.myMethod: String => Int

Example

scala
object Render:
  extension [A](a: A) def render: String = "Hi"
  extension [B](b: B) def render(using DummyImplicit): Char = 'x'

def example = Render.render(42)

Error

scala
-- [E051] Reference Error: example.scala:5:21 ----------------------------------
5 |def example = Render.render(42)
  |              ^^^^^^^^^^^^^
  |Ambiguous overload. The overloaded alternatives of method render in object Render with types
  | [B](b: B)(using x$2: DummyImplicit): Char
  | [A](a: A): String
  |both match arguments ((42 : Int))
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | There are 2 methods that could be referenced as the compiler knows too little
  | about the expected type.
  | You may specify the expected type e.g. by
  | - assigning it to a value with a specified type, or
  | - adding a type ascription as in instance.myMethod: String => Int
   -----------------------------------------------------------------------------

Solution

scala
// Hint compiler using explicit argument or result type
object Render:
  extension [A](a: A) def render: String = "Hi"
  extension [B](b: B) def render(using DummyImplicit): Char = 'x'

def example: String = Render.render(42)
scala
// Or try to remove methods that might lead to amibgious results
import scala.annotation.targetName
object Render:
  extension [A](a: A) def render: String = "Hi"
  extension [B](b: B) @targetName("render") def renderChar(using DummyImplicit): Char = 'x'

def example = Render.render(42)
<!-- 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>