JulienD JulienD - 1 month ago 9
Scala Question

Scala: Return type of abstract method

I cannot figure out how to specify the return type of a method an abstract class A, if the same method of the concrete classes have different return (sub)types:

abstract class A {
def method: List[Common (?)] // I want to force all subclasses to define this method

class B1 extends A {
def method(a,b,c): List[Sub1] = {...}

class B2 extends A {
def method(a,b,c): List[Sub2] = {...}

I tried to define a common trait of

abstract class Common // or abstract class
case class Sub1 extends Common
case class Sub2 extends Common

but I keep getting this:

Compilation error[class B1 needs to be abstract,
since method "method" in class A of type => List[Common] is not defined]

If I don't define the return type in class A, I get the same error with
... type => Unit ...

How can I solve that?

m-z m-z
 def method: List[Common]

Is not the same as

 // returns `List[Common]` to simplify things, but it would be the same if we returned a sub-type
 def method(a: ?, b: ?, c: ?): List[Common] = {...}

The first is a parameterless method that returns a List[Common], and the second is a method with three parameters that returns a List[Common]. The compiler sees these as two completely different methods. The fact that they have the same name means nothing.

The compiler is complaining because def method: List[Common] is not defined in the subclasses of A.