E058: Does Not Conform To Self Type

This error is emitted when a class's self type does not conform to the self type of a trait it extends.

A self type annotation (like self: SomeType =>) declares that any concrete class implementing this trait must also conform to SomeType. When extending such a trait, the extending class must satisfy this requirement.


Example

trait HasLogger:
  self: Logger =>
  def log(msg: String): Unit

trait Logger:
  def write(msg: String): Unit

class MyClass extends HasLogger:
  def log(msg: String): Unit = println(msg)

Error

-- [E058] Type Mismatch Error: example.scala:8:6 -------------------------------
8 |class MyClass extends HasLogger:
  |      ^
  |illegal inheritance: self type MyClass of class MyClass does not conform to self type Logger
  |of parent trait HasLogger
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | I tried to show that
  |   MyClass
  | conforms to
  |   Logger
  | but none of the attempts shown below succeeded:
  |
  |   ==> MyClass  <:  Logger  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

Solution

// Mix in the required trait
trait HasLogger:
  self: Logger =>
  def log(msg: String): Unit

trait Logger:
  def write(msg: String): Unit

class MyClass extends HasLogger with Logger:
  def log(msg: String): Unit = println(msg)
  def write(msg: String): Unit = println(msg)
// Or add a matching self type to the extending class
trait HasLogger:
  self: Logger =>
  def log(msg: String): Unit

trait Logger:
  def write(msg: String): Unit

abstract class MyClass extends HasLogger:
  self: Logger =>
  def log(msg: String): Unit = println(msg)