Learn The Scala Class And Type Hierarchy
Overview
In this tutorial, we will have a closer look at Scala's type hierarchy. To help you visualize the type hierarchy in Scala, you can refer to the diagram below which is a snapshot from Scala's documentation on Unified Types.
The diagram shows that the type Any is at the top most of the Scala's class hierarchy.
If you are coming from Java or .NET, you can think of the Any type as the Object class. In other words, Any is the root type and it has two sub-classes namely AnyVal and AnyRef as per the above diagram.
So where are the built-in primitive types such as the ones we have in Java? The answer is simple, there are none!
Steps
1. Declare a variable of type Any
If you recall from the previous Type Inference tutorial, Scala is able to infer types.
But in this example let's type our immutable variable favoriteDonut as Any.
println("Step 1: Declare a variable of type Any")
val favoriteDonut: Any = "Glazed Donut"
println(s"favoriteDonut of type Any = $favoriteDonut")
You should see the following output when you run your Scala application in IntelliJ:
Step 1: Declare a variable of type Any
favoriteDonut of type Any = Glazed Donut
2. Declare a variable of type AnyRef
Let's declare another variable called donutName. But this time you will use the type AnyRef.
println("\nStep 2: Declare a variable of type AnyRef")
val donutName: AnyRef = "Glazed Donut"
println(s"donutName of type AnyRef = $donutName")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: Declare a variable of type AnyRef
donutName of type AnyRef = Glazed Donut
3. Declare a variable of type AnyVal
Let's now declare another variable donutPrice to be of type AnyVal and assign its value to 2.50.
println("\nStep 3: Declare a variable of type AnyVal")
val donutPrice: AnyVal = 2.50
println(s"donutPrice of type AnyVal = $donutPrice")
You should see the following output when you run your Scala application in IntelliJ:
Step 3: Declare a variable of type AnyVal
AnyVal donutPrice = 2.5
Summary
In this tutorial, we went over the following:
- How to declare a variable of type Any
- How to declare a variable of type AnyRef
- How to declare a variable of type AnyVal
Tip
- Don't forget that as we showed in the Pattern Matching tutorial that you can pattern match on the type of your variable to determine its type.
- This tutorial was inspired by Scala documentation on Class Hierarchy. You can refer to it for additional details.
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will go over Enumerations in Scala.