Saturday 26 September 2015

Value Classes

In Scala, the types Short, Int, Long, Float, Double, Boolean, Char, Byte, and Unit are called value types. All value types are subtypes of AnyVal in Scala's object model.  Instances of value types are not created on the heap, instead they are stored in registers or on the stack.

All other types are called reference types, because all instances of them are allocated on the heap and variables that refer to these instances actually refer to the corresponding heap locations.

The Value Classes impose below limits on what can be declared. They don't result in heap allocations for the wrappers.

class Dollar(val value: Float) extends AnyVal {
       override def toString = "$%.2f".format(value)
}

val benjamin = new Dollar(100)


1. The value has one and only one public val argument.
2. The type of the argument must not be a value class itself.
3. The value class doesn't define secondary constructors.
4. The value class defines only methods, but no other vals and vars.
5. The value class can't override equals and hashCode
6. The value class can't be subclassed.
7. The value class can only inherit from universal traits.


No comments:

Post a Comment