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?

Kilian Foth
111k45 gold badges301 silver badges323 bronze badges
asked Mar 14, 2013 at 19:37
3
  • my first guess is that it's the latter :P Commented Mar 14, 2013 at 20:33
  • 1
    You may want to look at this answer: stackoverflow.com/a/2558317/67566 Commented Mar 15, 2013 at 0:59
  • It would be nice to mark this as a duplicate. Commented Mar 15, 2013 at 1:33

2 Answers 2

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.

answered Mar 15, 2013 at 2:18
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.

answered Mar 14, 2013 at 21:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.