Class Hierarchy
The Scala class hierarchy has Any at the top, from which all other types derive. It splits into two main branches: AnyVal (value types) and AnyRef (reference types). Additionally, Nothing and Null are special types that serve specific purposes in the hierarchy.
Any
├── AnyVal
│ ├── Unit
│ ├── Boolean
│ ├── Char
│ ├── Byte
│ ├── Short
│ ├── Int
│ ├── Long
│ ├── Float
│ └── Double
├── AnyRef (alias: Object)
│ ├── String
│ ├── List
│ ├── Option
│ │ ├── Some
│ │ └── None
│ ├── Map
│ ├── Set
│ ├── ... (other classes and user-defined classes)
│ └── Null (subtype of every AnyRef type)
└── Nothing (subtype of every other type)
Key Points
Any
- The root of the type hierarchy.
- Defines common methods such as
==,!=,equals,hashCode, andtoString.
AnyVal
- The root class of value types, which includes Scala's primitive types.
- Subclasses:
Unit,Boolean,Char,Byte,Short,Int,Long,Float,Double.
AnyRef (alias Object)
- The root class of all reference types.
- Subclasses:
String,List,Option,Map,Set, and user-defined classes.
Option
- A container for an optional value.
- Subclasses:
Some(contains a value),None(represents the absence of a value).
Null
- A subtype of every reference type (
AnyRef). - Can be assigned to any reference type but not to value types.
- The
nullliteral is of typeNull.
Nothing
- A subtype of every other type (both
AnyValandAnyRef). - Represents the type of "no value" or "no normal return".
- Useful for functions that never return normally (e.g., throw an exception).
Examples
Value Types (AnyVal)
val unitValue: Unit = ()
val booleanValue: Boolean = true
val charValue: Char = 'A'
val byteValue: Byte = 1
val shortValue: Short = 1
val intValue: Int = 1
val longValue: Long = 1L
val floatValue: Float = 1.0f
val doubleValue: Double = 1.0
Reference Types (AnyRef)
val stringValue: String = "Hello, Scala!"
val listValue: List[Int] = List(1, 2, 3)
val optionValue: Option[Int] = Some(1)
val noneValue: Option[Int] = None
val mapValue: Map[String, Int] = Map("one" -> 1)
val setValue: Set[Int] = Set(1, 2, 3)
class UserDefinedClass
val userDefinedInstance = new UserDefinedClass
val nullValue: String = null
Special Types
Nothing
def fail(message: String): Nothing = throw new RuntimeException(message)
// This function never returns normally, so it has type Nothing
val failed = fail("This is an error")
// This line is never reached
println("This will never be printed")
None
val maybeValue: Option[Int] = None
maybeValue match
case Some(value) => println(s"Found value: $value")
case None => println("No value found")
// Output: No value found