如果具体类的相同方法具有不同的return(sub)类型,我无法弄清楚如何指定抽象类A的方法的返回类型:
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] = {...}
}
Run Code Online (Sandbox Code Playgroud)
我试图定义一个共同的特点Sub1和Sub2:
abstract class Common // or abstract class
case class Sub1 extends Common
case class Sub2 extends Common
Run Code Online (Sandbox Code Playgroud)
但我一直这样:
Compilation error[class B1 needs to be abstract,
since method "method" in class A of type => List[Common] is not defined]
Run Code Online (Sandbox Code Playgroud)
如果我没有在A类中定义返回类型,我会得到相同的错误... type => Unit ....
我怎么解决这个问题?
def method: List[Common]
Run Code Online (Sandbox Code Playgroud)
是不一样的
// 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] = {...}
Run Code Online (Sandbox Code Playgroud)
第一个是返回a的无参数方法,List[Common]第二个是返回a的三个参数的方法List[Common].编译器将这些视为两种完全不同的方法.它们具有相同名称的事实毫无意义.
编译器抱怨,因为def method: List[Common]没有在子类中定义A.
| 归档时间: |
|
| 查看次数: |
628 次 |
| 最近记录: |