Why does Scala Some not inherit from AnyVal so that it uses the value type feature and save the boxing costs?
Something like:
sealed trait TestOption[+A] extends Any {
def isEmpty: Boolean
def get: A
}
final case class TestSome[+A](val x: A) extends AnyVal with TestOption[A] {
def isEmpty = false
def get = x
}
case object TestNone extends TestOption[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}
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.
First proposed in SIP-15 and introduced in Scala 2.10. 0, value classes are a mechanism in Scala to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses. The following shows a very minimal value class definition: class Wrapper(val underlying: Int) extends AnyVal.
At a fundamental level: value classes define objects which, once created, never change their value. A variable of a value type may only be changed by re-assigning to that variable. When we wish to only modify some portion of a value class (one attribute, say), we are compelled to reassign the whole object.
From the documentation for Value Classes:
Summary of Limitations
A value class
- must have only a primary constructor with exactly one public, val parameter whose type is not a value class. (From Scala 2.11.0, the parameter may be non-public.)
- may not have specialized type parameters.
- may not have nested or local classes, traits, or objects
- may not define a equals or hashCode method.
- must be a top-level class or a member of a statically accessible object
- can only have defs as members. In particular, it cannot have lazy vals, vars, or vals as members.
- cannot be extended by another class.
The bold ones excludes Some
from being a Value Class as currently written. The second of these could probably be addressed by a slight change but the former kills it. You'd not be able to wrap another Value Class in Some
if Some were made a Value Class itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With