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

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

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

val repo = new Repository

Error

-- [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

// 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"
// 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