Back to Scala3

E057: Does Not Conform To Bound

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

3.8.42.0 KB
Original Source

E057: Does Not Conform To Bound

This error is emitted when a type argument does not conform to the declared type bounds of a type parameter.

Type parameters can have upper bounds (<:) and lower bounds (>:). When you provide a type argument, it must satisfy these bounds. An upper bound means the type argument must be a subtype of the bound, while a lower bound means it must be a supertype.


Example

scala
trait A
trait B extends A
trait C extends B
class Contra[-T >: B]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???
    val c: Contra[C] = ???

Error

scala
-- [E057] Type Mismatch Error: example.scala:9:18 ------------------------------
9 |    val c: Contra[C] = ???
  |                  ^
  |                  Type argument C does not conform to lower bound B
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | I tried to show that
  |   B
  | conforms to
  |   C
  | but none of the attempts shown below succeeded:
  |
  |   ==> B  <:  C  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

Solution

scala
// Use a types that conforms to the bound
trait A
trait B extends A
trait C extends A

class Contra[-T >: B]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???

scala
// Or change the type bound if appropriate
trait A
trait B extends A
trait C extends B

class Contra[-T >: C]

def example =
    val a: Contra[A] = ???
    val b: Contra[B] = ???
    val c: Contra[C] = ???
<!-- 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>