Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have been reading about traits in Scala. They are pretty amazing. I am curious how they extend a class without actually resulting in multiple inheritance. I know that the JVM doesn't support multiple inheritance, so I am wondering how these extensions work. Is the language just providing syntactic sugar for composition? Or is the code within a trait duplicated in each class that uses it?

share|improve this question
    
my first guess is that it's the latter :P –  Esailija Mar 14 '13 at 20:33
1  
You may want to look at this answer: stackoverflow.com/a/2558317/67566 –  James Black Mar 15 '13 at 0:59
    
It would be nice to mark this as a duplicate. –  Travis Parks Mar 15 '13 at 1:33

2 Answers 2

up vote 3 down vote accepted

The language is "providing syntactic sugar for composition".

The trait methods become static methods on a helper class associated with the trait. See this reference.

share|improve this answer

As far as I remember, it's actually a combination of both plus a whole bunch of optimization tricks. It's a pretty tricky encoding, actually.

Your best bet is probably to just compile some simple examples and decompile the resulting .class files.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.