Back to Scala3

E180: Ambiguous Extension Method

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

3.8.42.3 KB
Original Source

E180: Ambiguous Extension Method

This error occurs when multiple extension methods with the same name are applicable to a type and the compiler cannot determine which one to use.

When multiple extension methods from different imports are both valid for a receiver type, the call is ambiguous and the compiler reports this error.

Note: This error is always reported as a nested error inside E008 (Not Found Error) because extension method resolution failures are wrapped in member lookup errors. The E180 message appears in the detailed error explanation.


Example

scala
object Ext1:
  extension (i: Int)
    def wow: Unit = println(i)

object Ext2:
  extension (i: Int)
    def wow: Unit = println(i * 2)

def example(): Unit =
  import Ext1.wow
  import Ext2.wow
  5.wow  // error: ambiguous extension methods

Error

When compiled, this produces an E008 error with the E180 ambiguous extension method message nested inside:

scala
-- [E008] Not Found Error: example.scala:12:2 ----------------------------------
12 |  5.wow
   |  ^^^^^
   |  value wow is not a member of Int.
   |  An extension method was tried, but could not be fully constructed:
   |
   |      Ext2.wow(5)
   |
   |      failed with:
   |
   |          Ambiguous extension methods:
   |          both Ext2.wow(5)
   |          and  Ext1.wow(5)
   |          are possible expansions of 5.wow

Solution

Disambiguate by using a qualified name:

scala
object Ext1:
  extension (i: Int)
    def wow: Unit = println(i)

object Ext2:
  extension (i: Int)
    def wow: Unit = println(i * 2)

def example(): Unit =
  import Ext1.wow
  import Ext2.wow
  Ext1.wow(5)  // explicitly call Ext1's version

Or import only one extension method:

scala
object Ext1:
  extension (i: Int)
    def wow: Unit = println(i)

object Ext2:
  extension (i: Int)
    def wow: Unit = println(i * 2)

def example(): Unit =
  import Ext1.wow  // only import Ext1's extension
  5.wow  // unambiguous
<!-- 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>