Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are traits instantiable?

Tags:

scala

As far as I've learned, traits in Scala are similar to interfaces in Java except methods are allowed to have an implementation. Also, in contrast to Scala classes, you can't pass them arguments for construction.

So far, so good. But why am I allowed to instantiate them? Really, I don't see a good reason to allow this.

like image 718
helpermethod Avatar asked Oct 15 '12 07:10

helpermethod


1 Answers

You don't really instantiate them. As you drew a parallel with Java, let's go further into it. You are able in Java to build a Anonymous class out of an abstract class or of an Interface. It is almost the same in Scala:

scala> trait A
defined trait A

scala> new A {}
res0: A = $anon$1@5736ab79

Note that the curly braces are mandatory when you create an object from a trait. For example, yon cannot do:

scala> new A
<console>:9: error: trait A is abstract; cannot be instantiated
              new A
              ^

While it would works perfectly for a class:

scala> class B
defined class B

scala> new B
res2: B = B@213526b0

Of course if some elements in your trait are not implemented, you need to implement them when you create the object:

scala> trait C {def foo: Int}
defined trait C

scala> new C {}
<console>:9: error: object creation impossible, since method foo in trait C of type => Int is not defined
              new C {}
                  ^

scala> new C {def foo = 42}
res4: C = $anon$1@744957c7
like image 68
Nicolas Avatar answered Oct 16 '22 22:10

Nicolas