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?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
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.
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