Traits is a concept used in Scala as well as in C++ (although in C++ it is more of an idiom than a concept integrated into the language). It is not obvious to me how the concepts are related though. What is the relation between Scala and C++ traits?
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
A Trait is a concept pre-dominantly used in object-oriented programming, which can extend the functionality of a class using a set of methods. Traits are similar in spirit to interfaces in Java programming language. Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters.
In Scala, we are allowed to implement the method(only abstract methods) in traits. If a trait contains method implementation, then the class which extends this trait need not implement the method which already implemented in a trait.
They're not related at all.
In C++, a traits class is a helper object that tells you something about a type that you can't get from the type name itself. C++ traits are actually more similar to Scala's def foo[A:Manifest]
notation (a feature for which I don't know the proper name.)
Scala's traits are actually a lot more like C++'s multiple inheritance (though they differ in the details). I'm actually quite disappointed that C++'s version of multiple inheritance has the official name "multiple inheritance" (to the exclusion of all of the other variations), because the first sentence of any explanation of Scala's traits should be "Traits are a form of multiple inheritance that ..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With