Scala 中抽象特征的语义 [英] Semantics of abstract traits in Scala
问题描述
我想知道将 abstract
关键字与 trait
结合使用的语义是什么.
I am wondering what the semantics of using the abstract
keyword in combination with a trait
is.
如果 trait 没有定义任何抽象方法,abstract
关键字不会阻止我创建一个实例:
If the trait does not define any abstract methods, the abstract
keyword does not prevent me from creating an instance:
scala> abstract trait T
defined trait T
scala> new T{}
res0: java.lang.Object with T = $anon$1@12cd927d
另一方面,如果 trait 确实定义了一个抽象方法,则无论 abstract
关键字是否存在,我都无法创建实例(当然不实现此方法):>
On the other hand, if the trait does define an abstract method, I cannot create an instance (without implementing this method of course) no matter if the abstract
keyword is present or not:
scala> abstract trait T { def foo : Unit }
defined trait T
scala> new T{}
<console>:9: error: object creation impossible, since method foo in trait T of type => Unit is not defined
new T{}
^
scala> trait T { def foo : Unit }
defined trait T
scala> new T{}
<console>:9: error: object creation impossible, since method foo in trait T of type => Unit is not defined
new T{}
^
那么 trait
前面的 abstract
关键字有什么用?
So what is the abstract
keyword in front of a trait
good for?
推荐答案
没有效果,traits 自动抽象.
It has no effect, traits are automatically abstract.
抽象修饰符用于类定义.它是多余的对于traits,对于所有其他不完整的类是强制性的会员.
The abstract modifier is used in class definitions. It is redundant for traits, and mandatory for all other classes which have incomplete members.
http://www.scala-lang.org/docu/files/ScalaReference.pdf
这篇关于Scala 中抽象特征的语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!