It's not a secret anymore!*
The moose likes Scala and the fly likes Scala Traits doubt. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Languages » Scala
Bookmark "Scala Traits doubt." Watch "Scala Traits doubt." New topic
Author

Scala Traits doubt.

vivek srivastava
Ranch Hand

Joined: Nov 30, 2007
Posts: 39
As I was reading about trait, it seems to me that this is same as abstract class.
Could anyone please clarify that :-
Can we assume Trait same as abstract class? If not, then what is the difference between these two?

Thanks,
Vivek
Daniel Gronau
Greenhorn

Joined: Oct 06, 2009
Posts: 1
Traits are like abstract classes, because you can have abstract or concrete methods. On the other hand traits are like interfaces, because they have no constructors, and a class can extend/implement more than one trait, which gives a limited form of "multiple inheritence" (behind the scene it is still single inheritance by a linearization process), but without many of the problems (like the diamond problem). Traits are not a new invention, they are used in other languages as well, but often under the name "Mix-in".

Traits are very flexible and can be used in several pattern, which are not possible with abstract classes and/or interfaces, see e.g. http://www.artima.com/scalazine/articles/selfless_trait_pattern.html or http://www.artima.com/scalazine/articles/stackable_trait_pattern.html

Deron Fuller
Greenhorn

Joined: Mar 03, 2009
Posts: 6
I believe the difference is that Traits allow you to define abstract members as well as full method definitions.

I've only recently begun to learn scala but I think this link is a good summation of scala's abstract classes and traits from a java programmers point of view.

http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5

vivek srivastava
Ranch Hand

Joined: Nov 30, 2007
Posts: 39
Thanks! I got your point. So we can say that "trait" is like an abstract class in java with the difference that we can use trait in multiple inheritance with "extends" and "with" keyword.
Inca Nauthiz
Greenhorn

Joined: Nov 21, 2008
Posts: 8
Trait is much more similar to Java interface than to abstract class. As it was mentioned before, trait does not have constructor – it implies that trait is not meant for instantiation by itself.
It is generally used to add some stuff to existing classes. And all interface-related patterns are implemented with traits, too.


If you use Scala, please try my Web framework and ORM and let me know, what you think about it. TIA.
 
GeeCON Prague 2014
 
subject: Scala Traits doubt.