E042: Cannot Instantiate Abstract Class Or Trait

This error is emitted when attempting to directly instantiate an abstract class or a trait using new.

Abstract classes and traits need to be extended by a concrete class or object to make their functionality accessible. You cannot create instances of them directly.


Example

trait Animal:
  def speak(): String

val pet = new Animal

Error

-- [E042] Type Error: example.scala:4:14 ---------------------------------------
4 |val pet = new Animal
  |              ^^^^^^
  |              Animal is a trait; it cannot be instantiated
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Abstract classes and traits need to be extended by a concrete class or object
  | to make their functionality accessible.
  |
  | You may want to create an anonymous class extending Animal with
  |   class Animal { }
  |
  | or add a companion object with
  |   object Animal extends Animal
  |
  | You need to implement any abstract members in both cases.
   -----------------------------------------------------------------------------

Solution

// Create an anonymous class implementing the trait
trait Animal:
  def speak(): String

val pet = new Animal:
  def speak(): String = "Woof!"
// Or create a concrete class that extends the trait
trait Animal:
  def speak(): String

class Dog extends Animal:
  def speak(): String = "Woof!"

val pet = new Dog
// For abstract classes, same approach applies
abstract class Animal:
  def speak(): String

class Cat extends Animal:
  def speak(): String = "Meow!"

val pet = new Cat