값 클래스는 보조 생성자를 정의할 수 없음

값 클래스는 보조 생성자를 정의할 수 없음 (Value Classes May Not Define A Secondary Constructor)

값 클래스(AnyVal을 상속한 클래스)가 보조 생성자를 정의했을 때 나오는 에러예요.

출처: Scala 3 Reference

본문

값 클래스(AnyVal을 상속한 클래스)가 보조 생성자(secondary constructor)를 정의하면 이 에러가 발생해요.

값 클래스는 정확히 하나의 val 매개변수를 가진 주 생성자 하나만 가질 수 있어요. 보조 생성자는 값 클래스의 최적화를 복잡하게 만들 수 있어서 허용되지 않아요.

예시

class Wrapper(val value: Int) extends AnyVal:
  def this(s: String) = this(s.toInt)

에러 메시지

-- [E072] Syntax Error: example.scala:2:6 --------------------------------------
2 |  def this(s: String) = this(s.toInt)
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |  Value classes may not define a secondary constructor

해결 방법

// Use a companion object factory method instead
class Wrapper(val value: Int) extends AnyVal

object Wrapper:
  def fromString(s: String): Wrapper = new Wrapper(s.toInt)
// Or use a regular class if you need multiple constructors
class Wrapper(val value: Int):
  def this(s: String) = this(s.toInt)

더 알아보기

  • 보조 생성자 역할은 컴패니언 객체의 팩토리 메서드로 대신하고, 여러 생성자가 꼭 필요하다면 일반 클래스를 쓰면 돼요.