E164: 오버라이드 에러예요
E164: 오버라이드 에러예요 (Override Error)
메서드 오버라이드가 오버라이드 규칙을 위반할 때 발생하는 에러예요. 보통 오버라이드하는 메서드가 호환되지 않는 반환 타입을 갖거나, 오버라이드 대상 메서드의 시그니처와 제대로 맞지 않을 때 발생해요.
본문
메서드 오버라이드가 유효하려면, 오버라이드하는 메서드의 반환 타입이 오버라이드 대상 메서드의 반환 타입의 하위 타입(subtype)이어야 하고(공변·covariance), 파라미터 타입은 상위 타입(supertype)이어야 해요(반공변·contravariance).
Example
class Base {
def foo: String = "hello"
}
class Derived extends Base {
override def foo: Int = 42
}
Error
-- [E164] Declaration Error: example.scala:6:15 --------------------------------
6 | override def foo: Int = 42
| ^
| error overriding method foo in class Base of type => String;
| method foo of type => Int has incompatible type
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| I tried to show that
| => Int
| conforms to
| => String
| but none of the attempts shown below succeeded:
|
| ==> => Int <: => String
| ==> Int <: String = false
|
| The tests were made under the empty constraint
-----------------------------------------------------------------------------
Solution
class Base {
def foo: String = "hello"
}
class Derived extends Base {
// Return type must be String or a subtype
override def foo: String = "world"
}
// If different behavior is needed, use a different method name
class Base {
def foo: String = "hello"
}
class Derived extends Base {
def fooInt: Int = 42
}
더 알아보기
- 공변(covariance)과 반공변(contravariance)에 대한 자세한 내용은 Scala 3 Reference의 타입 시스템 문서를 참고하세요.