Value Class in Scala

Scala | Value Class: In this tutorial, we are going to learn about the value class with its usages, syntax, and examples.
Submitted by Shivang Yadav, on June 29, 2020

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.


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.

Some points to remember about value class,

  1. The main purpose of value class is to optimize the program by avoiding run time allocations.
  2. The value class cannot be inherited by other classes.
  3. The value class cannot be nested.
  4. The value class is used to redefine all value types except the hashCode and equals.
  5. 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 ")


Scala Scala 


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.

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.