开发者

Why does `ScalaObject` exist?

Why do all Scala classes inherit from ScalaObject although that trait is completely empty and has no (visible?) functi开发者_运维知识库onality compared to AnyRef, which does define additional methods?

Won't that slow down method calls like equals() or hashCode() because it will need to take another class into consideration (which might override the methods)?

Isn't it possible to fold AnyRef and ScalaObject into one class?

UPDATE: ScalaObject was eradicated with new 2.10 version of Scala.


ScalaObject inserts a $tag method, which, according to the comment in the library source code for 2.7, "is needed for optimizing pattern matching expressions which match on constructors of case classes." Since the name starts with $, it should of course be considered "hidden" to application programmers. In Scala 2.8, it's entirely empty, so I guess it's there for backward compatibility.


Method dispatching does not chain up the class inheritance structure looking for implementations. The compiler constructs a net method dispatch table for each class that reflects its net override / inherited method lineage. It's one of the virtues of statically resolving all typing.


It also makes a handy hook for static analyses. For instance, imagine you had a tool which could search through a code base (compiled or not), and tell you that you could improve some metric of cohesiveness/coupling/layer-balance/what-have-you by extracting a trait from these classes and create an implicit conversions for those classes. This tool would sensibly only report on traits that could profitably be extract from classes that inherit ScalaObject, while reporting profitable implicit conversions from any Java class. The same tool would report on any possible "null" returns from ScalaObject sub-classes (where Option or similar is usually a better choice), while ignoring null returns from Java classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜