i’m starting with Scala and i found this a little weird. In java i could do something like this:
interface Foo{}
public class Bar implements Foo{}
I’m trying to do something similar with Scala, but it doesn’t work:
trait Foo;
class Bar with Foo; // This doesn't work!
I have to use the “extends” keyword:
class Bar extends Foo; // This works OK!
Now, it’s fine, but it’s not what i wanted.
Another thing weird i noted is that given every class in Scala extends from AnyRef (see this image from scala-lang.org: http://www.scala-lang.org/sites/default/files/images/classhierarchy.png) i can do this:
class Bar extends AnyRef with Foo; // This works too!
So, what am i missing? Doesn’t have sense to use a trait without extending it?
Thank you!
First note that the extends/implements difference tells nothing to the compiler than it would not know. I don’t mean that it is bad, just that the language could have done otherwise. In C#, you write
class A : B, C, Dinstead of bothclass A extends B implements C, Dandclass A implements B, C, D. So you can just think that Scala’sextendsis like the colon andwithlike the comma.Yet, in the old times, it used to be
class Bar with Foo. It changed when Scala went 2.0 back in 2006. See the change history.I think I remember (not sure) that the reason was simply that
class Bar with Foodoes not read well.In Scala,
A with Bis the intersection of typesAandB. An object is of typeA with Bif it is both of typeAand of typeB. Soclass A extends B with Cmay be readclass Aextends the typeB with C. No such thing withclass A with B.