Questions on Scala's class hierarchy:
In the IntelliJ IDE, I am looking for the implementation of Any
and AnyRef
, but they are not there.
Where are they defined and how can I see their code?
I read the following in "Programming in Scala"
The only case where == does not directly call equals is for Java's boxed numeric classes, such as Integer or Long. In Java, a new Integer(1) does not equal a new Long(1) even though for primitive values 1 == 1L. Since Scala is a more regular language than Java, it was necessary to correct this discrepancy by special-casing the == method for these classes.
Hmm... but isn't ==
final? How did they make a special case for Java's numeric classes?
Show the Type Hierarchy. Displays the type in its full context (i.e., superclasses and subclasses) in the Type Hierarchy view. Show the Supertype Hierarchy. Displays the supertypes and the hierarchy of all implemented interfaces of the type. Note: The selected type is always at the top level, in the upper-left corner.
Any is the superclass of all classes, also called the top class. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses: AnyVal.
In Scala, every class inherits from a common superclass named Any. Because every class is a subclass of Any, the methods defined in Any are "universal" methods: they may be invoked on any object.
A type class is an abstract, parameterized type that lets you add new behavior to any closed data type without using sub-typing. If you are coming from Java, you can think of type classes as something like java.
Any
, AnyRef
, Null
, and Nothing
do not actually exist; they are included to make the type system complete, but they have no real representation. You can find a reference in Scala's repository, but as it says, these do not actually compile and exist for documentation and bootstrapping purposes only. Scala's 3 Any*
s are actually all java.lang.Object
in the compiled bytecode.
Additionally, the primitive value classes (Int
, Long
, etc.) are all defined final abstract
, meaning that they also do not actually exist. All of their methods are abstract.
In order to make everything look neat and tidy, and more importantly, work, it is the compiler's job to fake the existence of these types and perform magic to make it all stick together. This is what allows ==
to do null-checking and properly handle value types even though it's final
, as the compiler is doing magic around it. In the case of new java.lang.Integer(5) == new java.lang.Long(5)
, it boils down to scala.runtime.BoxesRuntime.equalsNumNum(new java.lang.Integer(5), new java.lang.Long(5))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With