Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why classes that don't extends other classes must extend from traits? (with doesn't work)

Tags:

scala

traits

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!

like image 648
santiagobasulto Avatar asked Nov 09 '11 20:11

santiagobasulto


People also ask

What happens when a class extends another class?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

Can traits extend classes?

Traits are reusable components that can be used to extend the behavior of classes. They are similar to interfaces and contain both abstract and concrete methods and properties.

Which class is extended by all other classes?

Object class is superclass of all classes. Class Object is the root of the class hierarchy. Every class has Object as a superclass.


1 Answers

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, D instead of both class A extends B implements C, D and class A implements B, C, D. So you can just think that Scala's extends is like the colon and with like 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 Foo does not read well.

In Scala, A with B is the intersection of types A and B. An object is of type A with B if it is both of type A and of type B. So class A extends B with C may be read class A extends the type B with C. No such thing with class A with B.

like image 94
Didier Dupont Avatar answered Nov 15 '22 23:11

Didier Dupont