Home »
Scala
Value Class in Scala
By IncludeHelp Last updated : November 01, 2024
Value Classes
Value classes are a special mechanism in Scala that is used to help the compiler to avoid allocating run time objects.
This is done by defining a subclass of AnyVal. The only parameter it excepts is the datatype whose value is to be redefined. This is used to redefine all value types except the hashCode and equals.
The value types that can be redefined are Char, Int, Float, Double, Long, Short, Byte, Unit, and Boolean.
Syntax
The syntax for creating a value class in Scala,
case class class_name(val val_ name : datatype) extends AnyVal
The value class can have methods that are used to redefine the values or wrap the value used at the time of object creation to a different value.
Points to remember
Some points to remember about value class,
- The main purpose of value class is to optimize the program by avoiding run time allocations.
- The value class cannot be inherited by other classes.
- The value class cannot be nested.
- The value class is used to redefine all value types except the hashCode and equals.
- It can have only methods (def) as its member i.e. no variable is allowed.
Scala program to understand the concept of value class
// Program to show the working of
// value class in Scala
class valueClass(val str: String) extends AnyVal {
def doubleprint() = str + str
}
object myObject {
def main(args: Array[String]) {
val obj = new valueClass("Scala ")
println(obj.doubleprint())
}
}
Output
Scala Scala
Explanation
Here, we have created a value class in Scala named valueClass for string type which has a function named doubleprint that stores the string twice in the object.
Generally, the value Class is used to store the same data as in the object and it just functions to improve the performance.
What value class does?
The value class acts as a wrapper class to other types. And the instances of wrapper class are not created at the compile time which improves the performance as less initialization is to be done and compiler time.