I am wondering what the semantics of using the abstract
keyword in combination with a trait
is.
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
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?
Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.
In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class. The abstract methods of abstract class are those methods which do not contain any implementation.
Although Scala has abstract classes, it's much more common to use traits than abstract classes to implement base behavior. A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With