Back to Scala3

E220: Default Shadows Given

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

3.8.42.3 KB
Original Source

E220: Default Shadows Given

This warning is emitted when a default argument is used for an implicit parameter even though there is a given instance in scope.

When you explicitly provide some using arguments but not all, the remaining implicit parameters are filled using default arguments rather than searching for given instances. This can lead to surprising behavior where a given in scope is ignored.


Example

scala
def f(using s: String, i: Int = 1): String = s * i

def example: String =
  given Int = 2
  f(using s = "ab")

Error

scala
-- [E220] Type Warning: example.scala:5:3 --------------------------------------
5 |  f(using s = "ab")
  |  ^^^^^^^^^^^^^^^^^
  |  Argument for implicit parameter i was supplied using a default argument.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Usually the given in scope is intended, but you must specify it after explicit `using`.
   -----------------------------------------------------------------------------

Solution

If you want to use the given in scope, specify it explicitly after the using keyword:

scala
def f(using s: String, i: Int = 1): String = s * i

def example: String =
  given Int = 2
  f(using s = "ab", i = summon[Int])

Or use separate parameter clauses so the given is resolved properly:

scala
def g(using s: String)(using i: Int = 1): String = s * i

def example: String =
  given Int = 2
  g(using s = "ab")  // given Int is used from the second clause

If you intentionally want to use the default argument, you can suppress the warning by explicitly passing the default value:

scala
def f(using s: String, i: Int = 1): String = s * i

def example: String =
  given Int = 2
  f(using s = "ab", i = 1)  // explicit default value, no warning
<!-- 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>