Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scala Traits doubt.

 
vivek srivastava
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic