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?
-
my first guess is that it's the latter :PEsailija– Esailija2013年03月14日 20:33:30 +00:00Commented Mar 14, 2013 at 20:33
-
1You may want to look at this answer: stackoverflow.com/a/2558317/67566James Black– James Black2013年03月15日 00:59:02 +00:00Commented Mar 15, 2013 at 0:59
-
It would be nice to mark this as a duplicate.Travis Parks– Travis Parks2013年03月15日 01:33:06 +00:00Commented Mar 15, 2013 at 1:33
2 Answers 2
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 .class
files.