scala3
scala3 copied to clipboard
JEP 401: Project Valhalla value classes
I implemented Project Valhalla's value classes. The documentations are in docs/_docs/reference/experimental/valhalla.md and I have copied it below as well.
As per JEP 401, there is a new attribute LoadableDescriptors in the class files. Thus, this PR depends on modifications in the scala-asm repo. Here is my fork of it for anyone who wants to try it out.
You should use the flag --Yvalue-classes to compile any value classes, since this changes the class file's major and minor version to be compatible with Project Valhalla's JVM.
Documentation
Valhalla Value Classes
Valhalla value classes are the Scala equivalence of Java's Project Valhalla's value classes (see JEP 401). When used with the Project Valhalla JVM, Valhalla value classes are optimized.
Valhalla value classes extend AnyVal and have a valhalla annotation. Valhalla value classes cannot have non-parameter fields and cannot have auxilliary constructors.
Valhalla value classes do not have object identity -- two valhalla value classes are equal when their fields are the same.
import scala.annotation.valhalla
@valhalla class ValhallaValueClass(val x: Int, val y: Int) extends AnyVal
Valhalla value classes are implicitly final and cannot be extended unless it is abstract. Its fields are immutable and cannot be lazy.
Valhalla value classes can extend AnyVal, universal traits, or abstract valhalla value classes.
Valhalla Traits
Valhalla Traits are Universal Traits (traits that extend Any) with a valhalla annotation.
Like Valhalla value classes, any Valhalla trait must have immutable fields only.
Valhalla traits can extend Any or universal traits.
import scala.annotation.valhalla
@valhalla trait(val x: Int, val y: Int) ValhallaTrait extends Any
Using Explicit Self with Valhalla
Valhalla traits can have self-type of any trait without mutable fields.
CanEqual with Valhalla
Valhalla value classes can be null, so the CanEqual of null and a valhalla value class returns true.