Scala:“类型A = XXX"和“最终类型A = XX"之间的区别? [英] Scala: Difference between 'type A = XXX' and 'final type A = XX'?

查看:73
本文介绍了Scala:“类型A = XXX"和“最终类型A = XX"之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个抽象类型AA和一个具体类型XXX:

assuming I have an abstract type AA and concrete type XXX:

trait AA {
  type A = XXX
  final type B = XXX
}

在这种情况下,在任何AA子类中,类型A和B都不能被覆盖,因此关键字final看起来是完全多余的.这句话正确吗?

In this case in any subclass of AA, both type A and B cannot be overriden, so it appears that the keyword final is completely redundant. Is this statement correct?

推荐答案

很难证明它们是完全相同的,但是我要指出的是,它们减去了一些无用的怪癖.

It's hard to prove that they're exactly identical, but I'm going to argue that they are, minus a few useless quirks.

首先也是最明显的是,它们给出不同的错误消息.但这还不是全部:从技术上讲,可以覆盖A,您只能将其覆盖到XXX以外的任何其他内容:

First and most obviously, they give different error messages. But that's not all: it's technically possible to override A, you just can't override it to anything other than XXX:

trait A1 extends AA {
  override type A = XXX  // Compiles, but doesn't really do anything.
}

另一方面,您永远无法覆盖B:

On the other hand, you can't ever override B:

trait A2 extends AA {
  override type B = XXX  // Does not compile.
}

有什么有用的区别吗?

再次,我要争论的是没有.在问题答案中-it-possible-to-override-a-type-field>是否可以覆盖类型字段,StackOverflow用户 0__ 指出

Are there any useful differences?

Again, I'm going to argue that there aren't. In a very detailed answer to the question Is it possible to override a type field, StackOverflow user 0__ notes that

type T = C不可避免地会修复T,这在某种程度上相当于制作方法final.

type T = C inevitably fixes T, which would kind of correspond to making a method final.

您现在可以轻松地看到必须禁止它进一步覆盖" T

之后是有关如果您可以将T覆盖为其他类型,类型系统将如何不一致的一些说明.有关详细信息,请参见该答案.

followed by some explanation of how the type system would be inconsistent if you could override T to a different type. See that answer for the details.

这篇关于Scala:“类型A = XXX"和“最终类型A = XX"之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆