Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relation between Scala and C++ traits

Tags:

c++

scala

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?

like image 772
Tobias Furuholm Avatar asked Mar 06 '11 17:03

Tobias Furuholm


People also ask

What is a Scala trait when do you use Scala 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.

What is the trait in Scala?

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.

Can traits have implementation in Scala?

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.


1 Answers

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 ..."

like image 183
Ken Bloom Avatar answered Sep 21 '22 23:09

Ken Bloom