E208: Extension Has Default Receiver

This warning occurs when an extension method has a default argument for its receiver parameter. This is discouraged because the default value would never be used when the extension method is invoked as a selection on an object.

Extension methods are typically invoked as receiver.method(), where the receiver is always provided. A default argument for the receiver makes sense only when calling the method as a regular function, but in that case it should not be defined as an extension.

Example

extension (s: String = "hello, world") def invert = s.reverse.toUpperCase

Error

-- [E208] Potential Issue Warning: example.scala:1:23 --------------------------
1 |extension (s: String = "hello, world") def invert = s.reverse.toUpperCase
  |                       ^
  |Extension method invert should not have a default argument for its receiver.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The receiver cannot be omitted when an extension method is invoked as a selection.
  | A default argument for that parameter would never be used in that case.
  | 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.
   -----------------------------------------------------------------------------

Explanation

The receiver cannot be omitted when an extension method is invoked as a selection. A default argument for that parameter would never be used in that case. 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.

Solution

Remove the default argument from the receiver parameter:

extension (s: String) def invert = s.reverse.toUpperCase

If you need a function with a default argument, define it as a regular method instead of an extension:

def invert(s: String = "hello, world"): String = s.reverse.toUpperCase

Note that default arguments are allowed for non-receiver parameters in extension methods:

extension (s: String)
  def combine(other: String = ", world") = s + other