假设我有一个抽象类型 AA 和具体类型 XXX:
trait AA {
type A = XXX
final type B = XXX
}
在这种情况下,在 AA 的任何子类中,类型 A 和 B 都不能被覆盖,因此出现关键字
final
是完全多余的。这个说法正确吗?
最佳答案
很难证明它们完全相同,但我会争辩说它们是,减去一些无用的怪癖。
无用的怪癖
首先也是最明显的是,它们给出了不同的错误信息。但这还不是全部:技术上可以覆盖 A
,您不能将其覆盖为 XXX
以外的任何内容:
trait A1 extends AA {
override type A = XXX // Compiles, but doesn't really do anything.
}
另一方面,您永远无法覆盖
B
:trait A2 extends AA {
override type B = XXX // Does not compile.
}
有什么有用的区别吗?
再一次,我要争辩说没有。在一个非常详细的answer问题 Is it possible to override a type field , StackOverflow 用户 0__注意到
type T = C
inevitably fixesT
, which would kind of correspond to making a methodfinal
.
和
You can now easily see that it must be forbidden to further 'override'
T
接下来是一些关于如果您可以覆盖
T
类型系统将如何不一致的解释到不同的类型。有关详细信息,请参阅该答案。
关于Scala: 'type A = XXX' 和 'final type A = XX' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151774/