값 클래스는 내부 클래스를 정의할 수 없음
값 클래스는 내부 클래스를 정의할 수 없음 (Value Classes May Not Define Inner Class)
값 클래스(AnyVal을 상속한 클래스) 안에 내부 클래스 정의가 있을 때 나오는 에러예요.
본문
값 클래스(AnyVal을 상속한 클래스) 안에 내부 클래스 정의가 있으면 이 에러가 발생해요.
값 클래스는 컴파일러가 최적화할 수 있도록 엄격한 제약을 가져요. 내부 클래스, 트레이트, 객체를 정의할 수 없는데, 값 클래스의 런타임 표현은 감싸진 값(wrapped value)뿐이고 온전한 객체가 아니기 때문이에요.
예시
class Wrapper(val value: Int) extends AnyVal:
class Inner
에러 메시지
-- [E070] Syntax Error: example.scala:2:8 --------------------------------------
2 | class Inner
| ^^^^^^^^^^^
| Value classes may not define an inner class
해결 방법
// Move the inner class outside the value class
class Inner
class Wrapper(val value: Int) extends AnyVal:
def process: Int = value * 2
// Or use a regular class if you need inner classes
class Wrapper(val value: Int):
class Inner
더 알아보기
- 내부 클래스를 값 클래스 바깥으로 옮기거나, 내부 클래스가 꼭 필요하다면 일반 클래스를 쓰면 돼요.