我想要一个方法来覆盖由另一个类扩展的抽象类中定义的类型。
这是一个简单的例子:
abstract class abstr_test{ def word: Int}
class sub_test(s :String) extends abstr_test{def word: String = s}
答案 0 :(得分:2)
您可以使用类型变量来完成此任务。
abstract class Test {
type A
def word: A
}
class SubTest(s: String) extends Test {
type A = String
def word: String = s
}
答案 1 :(得分:0)
只是为了解释为什么允许你想要的东西(而不是@ soote和答案所提供的)会是一个非常糟糕的主意。
假设您在方法范围内有val x: abstr_test
。然后你可以做val y: Int = x.word
。 x
来自哪里并不重要;如果你到达这一行(x
不是null
,并且word
的实现不会引发异常),那么y
必须是Int
;否则,def word: Int
甚至意味着什么?
但如果sub_test
扩展abstr_test
,则类型sub_test
的值也是abstr_test
的值;再一次,这只是" subtype"的含义。所以你实际上可以val x: abstr_test = new sub_test("not a number")
。 y
之后val y: Int = x.word
的价值应该是多少?