Scala中的抽象特征语义 [英] Semantics of abstract traits in Scala

查看:114
本文介绍了Scala中的抽象特征语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将抽象关键字与特征结合使用的语义是什么。

I am wondering what the semantics of using the abstract keyword in combination with a trait is.

如果特征未定义任何抽象方法,则 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

另一方面,如果特征确实定义了抽象方法,则无论是否存在 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{}
                  ^

那是什么特征前面的抽象关键字对吗?

So what is the abstract keyword in front of a trait good for?

推荐答案

它无效,特征是自动抽象的。

It has no effect, traits are automatically abstract.


在类中使用abstract修饰符定义。对于特征,它是多余的
,对于其他所有不完整
成员的类都是必需的。

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屋!

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