5

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?

3

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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