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

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

-- [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

// 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)
// 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)