
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - AnyRef Type
In Scala, AnyRef is an important base type for all reference types. AnyRef is the Scala equivalent of java.lang.Object in Java. We will discuss AnyRef in this post.
AnyRef in Scala
AnyRef is the counterpart of AnyVal in Scala. AnyVal represents value types but AnyRef represents reference types. So AnyRef is the Scala equivalent of java.lang.Object in Java. As a direct subtype of Any, AnyRef is a superclass for all reference types in Scala. It includes user-defined classes, arrays, and built-in types like String. Unlike AnyVal (which represents value types), AnyRef has all objects that can be allocated on the heap.

Syntax
You can use AnyRef when you work with reference types in Scala and do not know their specific class. It acts as a general placeholder. So it is easier to handle different reference types.
The syntax is −
val unknownRef: AnyRef = new MyClass()
In the above example, unknownRef is declared as a variable of type AnyRef. It is assigned an instance of MyClass. However, it can point to any reference type.
val stringRef: AnyRef = "Hello, Scala!" val listRef: AnyRef = List(1, 2, 3)
Here, stringRef and listRef show the usage of AnyRef with different reference types. Its flexibility in various data structures.
Example of Scala AnyRef Type
Try the following example program.
object Demo { class MyClass def main(args: Array[String]): Unit = { val unknownRef: AnyRef = new MyClass() println(unknownRef) val stringRef: AnyRef = "Hello, Scala!" val listRef: AnyRef = List(1, 2, 3) println(stringRef) println(listRef) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Demo$MyClass@<hashcode> Hello, Scala! List(1, 2, 3)
Key Characteristics of AnyRef Type
1. Object Methods
AnyRef provides methods that are universally available for all reference types:
- equals − Compares object equality.
- hashCode − Computes a hash code for the object.
- toString − Converts the object to a string representation and more.
2. Type Hierarchy
All user-defined classes, arrays, and other reference types are ultimately subclasses of AnyRef.
Differences Between Any, AnyVal, and AnyRef
1. Any
The root of Scala type hierarchy. It has both value and reference types.
2. AnyVal
It represents value types in Scala and is a superclass for primitive types like Int, Double, etc.
3. AnyRef
It is reference type and mirrors the functionality of java.lang.Object in Java.
Best Practices for Using AnyRef Type
1. Use Specific Types Over AnyRef
It is best to use more specific types over AnyRef whenever possible to maintain type safety and clarity.
For example, you should not use this,
def processItem(item: AnyRef): Unit = { // ... }
Instead, use specific type,
def processString(str: String): Unit = { // ... }
2. Use Options Instead of Null
You should use Option instead of using null values to represent the presence and absence of a value.
For example, you should avoid this,
val mightBeNull: AnyRef = getNullableValue()
You should use Option,
val mightBeEmpty: Option[AnyRef] = Option(getNullableValue())
3. Minimize Casting from AnyRef
You should minimize casting by using generics and type parameters. Because casting can lead to runtime errors.
For example, you should not use this,
val obj: AnyRef = "Hello" val str: String = obj.asInstanceOf[String]
You should minimize here,
def genericMethodT: T = { // ... } val result: String = genericMethod("Hello")
4. Use Pattern Matching
You should use pattern matching when you have a variable of type AnyRef and need to perform different actions based on its actual type.
For example,
object Demo { def describeType(x: AnyRef): String = x match { case s: String => "This is a String." case i: Int => "This is an Int." case _ => "This is another type." } def main(args: Array[String]): Unit = { val myValue: AnyRef = "Hello, World!" println(describeType(myValue)) } }
The output will be,
This is a String.