Scala | Value Classes

Value classes are a new mechanism which help to avoid allocating run time objects. AnyVal define value classes. Value classes are predefined, they coincide to the primitive kind of Java-like languages.
There are nine predefined value types : Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.

equals or hashCode cannot redefine by a value class. Value classes are mainly used to optimize performance and memory.

Let’s understand value classes with some example.

Example #1:




// Scala program to illustrate value class
  
// Creating a value class and extend with AnyVal
case class C(val name: String) extends AnyVal
  
// Creating object
object gfg
{
    // Main method
    def main (args: Array[String])
    {
        // Creating the instance of the ValueClass
        val c = new C("w3wiki")
        c match 
        {   
            // new C instantiated here
            case C("w3wiki") => println("Matched with w3wiki")
            case C(x) => println("Not matched with w3wiki")
        }
    }
}


Output:

Matched with w3wiki

In the above code, a value class defined with the help of case class, Here AnyVal define value class(C). value class consist one string parameter. When we will pass same string as in case statement then this will return true otherwise false.

 
Example #2:




// Scala program to illustrate value class
  
// Creating a value class and extend with AnyVal
class Vclass(val a: Int) extends AnyVal 
{
    // Defining method
    def square() = a*a
}
  
// Creating object
object gfg
{
    // Main method
    def main (args: Array[String])
    {
        // creating the instance of the ValueClass
        val v = new Vclass(5)
        println(v.square())
    }
}


Output:

25

As we can see, in above example, a value class created and representation is an int. The above code consist a def in the value class Vclass. Here Vclass is a user-defined value class that wraps the Int parameter and encapsulates a square method. To call the square method, create the object of the Vclass class as like: val v = new Vclass(5)

Some Restrictions of Value Classes –

  • A value class might not have specialized type parameters. may not have specialized type parameters.
  • A value class may not have nested or local classes, traits, or objects.
  • equals or hashCode cannot redefine by a value class.
  • A value class cannot have lazy vals, vars, or vals as members. It can only have defs as members.
  • No other class can extend a value class.