AnyVal is the root class of allvalue types, which describe values not implemented as objects in the underlying host system. Value classes are specified in Scala Language Specification, section 12.2.
The standard implementation includes nineAnyVal subtypes:
scala.Double,scala.Float,scala.Long,scala.Int,scala.Char,scala.Short, andscala.Byte are thenumeric value types.
scala.Unit andscala.Boolean are thenon-numeric value types.
Other groupings:
Thesubrange types arescala.Byte,scala.Short, andscala.Char.
Theinteger types include the subrange types as well asscala.Int andscala.Long.
Thefloating point types arescala.Float andscala.Double.
Prior to Scala 2.10,AnyVal was a sealed trait. Beginning with Scala 2.10, however, it is possible to define a subclass ofAnyVal called auser-defined value class which is treated specially by the compiler. Properly-defined user value classes provide a way to improve performance on user-defined types by avoiding object allocation at runtime, and by replacing virtual method invocations with static method invocations.
User-defined value classes which avoid object allocation...
must have a singleval parameter that is the underlying runtime representation.
can definedefs, but novals,vars, or nestedtraitss,classes orobjects.
typically extend no other trait apart fromAnyVal.
cannot be used in type tests or pattern matching.
may not overrideequals orhashCode methods.
A minimal example:
class Wrapper(val underlying: Int) extends AnyVal { def foo: Wrapper = new Wrapper(underlying * 19)}It's important to note that user-defined value classes are limited, and in some circumstances, still must allocate a value class instance at runtime. These limitations and circumstances are explained in greater detail in theValue Classes and Universal Traits.