Semantics of abstract traits in Scala

自古美人都是妖i 提交于 2019-12-04 22:57:31

It has no effect, traits are automatically 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

You're not creating an instance of the trait. Traits can't be instantiated.

You're creating an instance of an anonymous class extending the trait.

In general,

new __t__

is equivalent to

{ class __anonymous__ extends __t__; new __anonymous__ }

(where __anonymous__ is a fresh name of an anonymous class that is inaccessible to the user program).

This is detailed in section 6.10 Instance Creation Expressions of the Scala Language Specification.

So, the reason why you can create an instance in the first case, is because you're not creating an instance of the trait (which is abstract) but an object (which isn't).

In the second case, the reason why you can't create an instance is that if you inherit from something, whether that is a trait or a class, you ultimately have to implement its abstract methods somewhere along the inheritance chain in order to instantiate it. In the first case, there are no abstract methods to implement.

The abstract keyword itself makes no difference: traits are implicitly abstract, the keyword is redundant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!