Why should the scala class explicitly extend AnyRef

I saw some code from the library:

trait A extends scala.AnyRef trait B extends scala.AnyRef with A 

Why does A need to explicitly extend AnyRef ? Aren't all classes implicitly derived from AnyRef already?

Why does B need to extend AnyRef even though A has already done this? What is the difference to change the code above:

 trait A trait B extends A 
+8
scala
source share
2 answers

I would not say any difference.

From scala documentation

Custom classes define link types by default; those. always (indirectly) a subclass of scala.AnyRef .

For further proof of the point

 scala> trait A defined trait A scala> trait B extends A defined trait B scala> val a = new A { } a: A = $anon$1@2d6d8735 scala> val b = new B { } b: B = $anon$1@47f37ef1 scala> a.isInstanceOf[AnyRef] res4: Boolean = true scala> b.isInstanceOf[AnyRef] res7: Boolean = true 
+7
source share

You do not need to explicitly extend AnyRef. AnyRef is the equivalent of a Java object in Scala. By creating an instance of the class, this instance will distribute AnyRef implicitly, regardless of whether it was explicitly specified in one of its superclasses or not.

The following code just creates an anonymous class, so it also extends AnyRef implicitly:

 trait A val a = new A { } 

Here is an explanation from scala -lang.org:

The superclass of all Scala classes. Anyone has two direct subclasses of Scala.AnyVal and Scala.AnyRef, representing two different classes: value classes and reference classes. All value classes are predefined; they correspond to primitive types of Java-like languages. All other classes define reference types. User-defined classes define default link types; that is, always (indirectly) a subclass of Scala.AnyRef. Each custom class in Scala implicitly extends the Scala.ScalaObject trait. Classes from the infrastructure on which Scala runs (such as the Java runtime) do not extend Scala.ScalaObject. If Scala is used in the context of the Java runtime, then Scala.AnyRef corresponds to java.lang.Object. Note that the above diagram also shows implicit conversions called representations between value classes. Here is an example that demonstrates that both numbers, characters, logical values, and functions are objects, just like any other object:

http://docs.scala-lang.org/tutorials/tour/unified-types.html

Since Scala 2.10, you can also extend AnyVal. From scala -lang.org:

AnyVal is the root class of all value types that describe values ​​that are not implemented as objects in the host base system. Prior to Scala 2.10, AnyVal was a sealed tag. However, starting with Scala 2.10, you can define a subclass of AnyVal, called a custom value class, which is specially handled by the compiler. Properly defined user value classes provide a way to improve performance on user types by avoiding the placement of objects at run time and replacing virtual method calls with static method calls.

+2
source share

All Articles