AnyVal

scala.AnyVal
abstract open class AnyVal

AnyVal is the root class of all value 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 nine AnyVal subtypes:

scala.Double, scala.Float, scala.Long, scala.Int, scala.Char, scala.Short, and scala.Byte are the numeric value types.

scala.Unit and scala.Boolean are the non-numeric value types.

Other groupings:

Prior to Scala 2.10, AnyVal was a sealed trait. Beginning with Scala 2.10, however, it is possible to define a subclass of AnyVal called a user-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 single val parameter that is the underlying runtime representation.

  • can define defs, but no vals, vars, or nested traitss, classes or objects.

  • typically extend no other trait apart from AnyVal.

  • cannot be used in type tests or pattern matching.

  • may not override equals or hashCode 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 the Value Classes and Universal Traits.

Attributes

Graph
Supertypes
trait Matchable
class Any
Known subtypes
class Deferrer[A]
class Partial[T, U]
class Deferrer[A]
class UnwrapOp
class ArrayOps[A]
class SearchImpl[Repr, A]
class Shape
class StringOps
class DoubleMult
class DurationInt
class DurationLong
class IntMult
class LongMult
class RichBiFunctionAsFunction2[T, U, R]
class RichFunction2AsBiFunction[T, U, R]
class FutureOps[T]
class RichOption[A]
class RichOptional[A]
class RichBoolean
class RichByte
class RichChar
class RichDouble
class RichFloat
class RichInt
class RichLong
class RichShort
class Tuple2Zipped[El1, It1, El2, It2]
class Ops[T1, T2]
class Tuple3Zipped[El1, It1, El2, It2, El3, It3]
class Ops[T1, T2, T3]
class ChainingOps[A]
class MergeableEither[A]
class Boolean
class Byte
class Char
class Double
class Float
class UnliftOps[A, B]
class Int
class Long
class ElementWiseExtractor[A, B]
class ArrowAssoc[A]
class Ensuring[A]
class StringFormat[A]
class any2stringadd[A]
class Short
class Unit
class ValueOf[T]
Show all
In this article