E013: Object May Not Have Self Type
This error is emitted when an object definition includes a self type annotation. Objects in Scala cannot have self types.
Self types are used to declare that a class or trait requires another trait to be mixed in. However, objects are singleton instances and cannot be extended or mixed with other traits after their definition, making self types meaningless for objects.
Example
trait Foo
object Test { self: Foo => }
Error
-- [E013] Syntax Error: example.scala:3:14 -------------------------------------
3 |object Test { self: Foo => }
| ^^^^^^^^^^^^
| objects must not have a self type
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| objects must not have a self type:
|
| Consider these alternative solutions:
| - Create a trait or a class instead of an object
| - Let the object extend a trait containing the self type:
|
| object Test extends Foo
-----------------------------------------------------------------------------
Solution
// Create a trait or class instead of an object
trait Foo
class Test extends Foo
// Or let the object extend the trait directly
trait Foo
object Test extends Foo
// Or use a class with a self type if you need the pattern
trait Foo
trait Bar
class Test { self: Foo & Bar =>
// ...
}
In this article