Back to Scala3

E146: Illegal Parameter Initialization

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

3.8.42.4 KB
Original Source

E146: Illegal Parameter Initialization

This error occurs when a class extends multiple traits that define the same parameterized trait, but the argument passed to the trait parameter doesn't conform to the required intersection type.

When a class inherits from multiple traits that share a common parameterized base trait with different type arguments, the parameter type becomes an intersection of all the required types. The value passed to initialize the parameter must conform to this intersection type.


Example

scala
trait Base[+A](val value: A)
trait Derived[+B] extends Base[B]

class Example extends Derived[String] with Base[Int](42)

Error

scala
-- [E146] Type Mismatch Error: example.scala:4:53 ------------------------------
4 |class Example extends Derived[String] with Base[Int](42)
  |                                                     ^^
  |        illegal parameter initialization of value value.
  |
  |          The argument passed for value value has type: (42 : Int)
  |          but class Example expects value value to have type: String & Int
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | I tried to show that
  |   (42 : Int)
  | conforms to
  |   String & Int
  | but none of the attempts shown below succeeded:
  |
  |   ==> (42 : Int)  <:  String & Int
  |     ==> (42 : Int)  <:  String
  |       ==> Int  <:  String  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

Solution

scala
trait Base[+A](val value: A)
trait Derived[+B] extends Base[B]

// Provide a value that satisfies both type constraints
class Example extends Derived[Any] with Base[Any]("hello")
scala
trait Base[+A](val value: A)
trait Derived[+B] extends Base[B]

// Or use consistent types across the inheritance hierarchy
class Example extends Derived[String] with Base[String]("hello")
<!-- 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>