Back to Scala3

E059: Does Not Conform To Self Type Cannot Be Instantiated

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

3.8.42.2 KB
Original Source

E059: Does Not Conform To Self Type Cannot Be Instantiated

This error is emitted when attempting to instantiate a class that has a self type which the class itself doesn't satisfy.

When a class declares a self type, it promises that any instance will conform to that type. If the class doesn't implement or mix in the required types, it cannot be instantiated.


Example

scala
trait Database:
  def query(sql: String): String

class Repository:
  self: Database =>
  def findAll(): String = query("SELECT *")

val repo = new Repository

Error

scala
-- [E059] Type Mismatch Error: example.scala:8:15 ------------------------------
8 |val repo = new Repository
  |               ^^^^^^^^^^
  |Repository does not conform to its self type Database; cannot be instantiated
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | I tried to show that
  |   Repository
  | conforms to
  |   Database
  | but none of the attempts shown below succeeded:
  |
  |   ==> Repository  <:  Database  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

Solution

scala
// Implement the required self type when instantiating
trait Database:
  def query(sql: String): String

class Repository:
  self: Database =>
  def findAll(): String = query("SELECT *")

val repo = new Repository with Database:
  def query(sql: String): String = s"Executed: $sql"
scala
// Or create a concrete class that mixes in the required trait
trait Database:
  def query(sql: String): String

class Repository:
  self: Database =>
  def findAll(): String = query("SELECT *")

class SqlRepository extends Repository with Database:
  def query(sql: String): String = s"Executed: $sql"

val repo = new SqlRepository
<!-- 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>