Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semantics of abstract traits in Scala

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?

like image 242
Frank Avatar asked Feb 19 '12 12:02

Frank


People also ask

What is the difference between a trait and an abstract class in Scala?

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.

What are abstract methods in Scala?

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.

Can a trait extend an abstract class Scala?

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.

What is a Scala trait when do you use Scala traits?

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.


1 Answers

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

like image 173
retronym Avatar answered Nov 04 '22 16:11

retronym