AnyRef
AnyRef represents reference classes. All non-value types are defined as reference types.
- In Scala, AnyRef is the root class of all reference types and child of “Any” class in the Scala type system.
- These are types that refer to objects rather than directly holding values.
- Every custom type in Scala belongs to AnyRef category.
- User-defined classes define reference types by default; i.e. they always (indirectly) subclass scala.
- AnyRef. scala.AnyRef in java programming corresponds to java.lang.Object.
Example:
Scala
// Scala program of Scala Type hierarchy // Using AnyRef // Creating object object Geeks { // Main method def main(args : Array[String]) { val list : List[AnyRef] = List( "GFG", "w3wiki" ) list.foreach(element = > println(element)) } } |
Output
GFG w3wiki
Scala Type Hierarchy
There are no primitive types in Scala(unlike Java). All data types in Scala are objects that have methods to operate on their data. All of Scala’s types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically.
Any
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
- AnyRef
Example:
Scala
// Scala program of Scala Type hierarchy // Creating object object Geeks { // Main method def main(args : Array[String]) { val list : List[Any] = List( false , 66677 , 732 , 'a' , "abs" ) list.foreach(element = > println(element)) } } |
Output
false 66677 732 a abs