E042: Cannot Instantiate Abstract Class Or Trait — 추상 클래스나 트레이트는 인스턴스화할 수 없어요

E042: Cannot Instantiate Abstract Class Or Trait — 추상 클래스나 트레이트는 인스턴스화할 수 없어요

new를 사용해 추상 클래스나 트레이트를 직접 인스턴스화하려고 할 때 이 에러가 나와요.

출처: Scala 3 Reference

본문

추상 클래스와 트레이트는 그 기능을 사용할 수 있도록 구체적인 클래스나 객체로 확장(extend) 되어야 해요. 이들을 직접 인스턴스로 만들 수는 없죠.

예제 (Example)

trait Animal:
  def speak(): String

val pet = new Animal

Animal은 추상 멤버 speak가 있는 트레이트인데, 이를 구현하는 구체 클래스 없이 그냥 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

더 알아보기 (Learn more)