E164: Override Error
This error occurs when a method override violates override rules, typically when the overriding method has an incompatible return type or doesn't properly match the signature of the method it's overriding.
For a method override to be valid, the overriding method's return type must be a subtype of the overridden method's return type (covariance), and parameter types must be supertypes (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
}
In this article