Back to Scala3

E194: Extension Nullified by Member

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

3.8.42.4 KB
Original Source

E194: Extension Nullified by Member

This warning is emitted when an extension method will never be selected because the target type already has a member with the same name and compatible parameter types.

Extensions can be overloaded, but they do not overload existing member methods. When you call a method on a value, the compiler will always prefer the existing member method over an extension method with the same signature.


Longer explanation:

Although extensions can be overloaded, they do not overload existing member methods. An extension method can be invoked as a regular method, but if that is the intended usage, it should not be defined as an extension.

The extension may be invoked as though selected from an arbitrary type if conversions are in play.


Example

scala
class Person

object PersonOps:
  extension (p: Person) def toString: String = "custom"

Error

scala
-- [E194] Potential Issue Warning: example.scala:4:28 --------------------------
4 |  extension (p: Person) def toString: String = "custom"
  |                            ^
  |Extension method toString will never be selected from type Person
  |because Person already has a member with the same name and compatible parameter types.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Although extensions can be overloaded, they do not overload existing member methods.
  | An extension method can be invoked as a regular method, but if that is the intended usage,
  | it should not be defined as an extension.
  |
  | The extension may be invoked as though selected from an arbitrary type if conversions are in play.
   -----------------------------------------------------------------------------

Solution

Use a different method name:

scala
class Person

object PersonOps:
  extension (p: Person) def toCustomString: String = "custom"

Or override the method in the class itself:

scala
class Person:
  override def toString: String = "custom"
<!-- 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>