Over a million developers have joined DZone.

What Is a Value Class in Scala?

DZone 's Guide to

What Is a Value Class in Scala?

Want to learn more about using the value class in Scala? Check out this tutorial where we demonstrate what and when to use value classes in your project.

· Java Zone ·
Free Resource

Value classes are a mechanism in Scala that help to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses. The following shows a very minimal value class definition:

case class UserId(id: Int) extends AnyVal

As you can see in the above section, for a class to be a value class, it must have exactly one parameter and have nothing inside — except defs. Furthermore, no other class can extend a value class, and a value class cannot redefine equals or hashCode. To define a value class, make it a subclass of  AnyVal and put theval keyword before the one parameter. This is how you can recognize or create value classes in Scala.

Why Do We Need Value Classes?

Fundamentally, a value class is one that wraps around a very simple type or a simple value, like Int,  Boolean, etc. What that means is that, at compile time, you see the value class and use the value class, but at the time bytecode could get generated, you are actually using the underlying simple type. So, that means that your instances of the wrapper classes creator, which means less initialization, increase performance and create less memory usage, because there is no instance of the wrapper classes.

Value classes are mostly used for performance optimization and memory optimization. You can think of many of these classes as your Scala typical primitive, like classes IntBoolean,  Double, etc. Use cases where you would want to and where you could apply value classes is for tiny types. Let’s look at a couple of examples of how that can be applied.

case class User(id: Int, name: String)

case class Tweet(id: Int, content: String)

object Test extends App{

  val user = User(1, "Kunal")
  val tweet = Tweet(11, "Scala Rocks")

  println(s"User ID :- ${user.id}")
  println(s"Tweet Content:- ${tweet.content}")

In the above example, we have a very simple data model where we have User and Tweet. Note that we’re using Intfor two types that are really unrelated — a user ID and tweeter ID are completely different, so we might want to differentiate it. The rest of this code is nothing special.

Now, what happens if I want to use the concept of tiny types? Let’s go through one more example where we are using tiny types:

case class UserId(id: Int)

case class Username(name: String)

case class TweetId(id: Int)

case class TweetContent(content: String)

case class User(id: UserId, name: Username)

case class Tweet(id: TweetId, content: TweetContent)

object Test extends App {
  val user = User(UserId(1), Username("kunal"))

  val tweet = Tweet(TweetId(11), TweetContent("ABC"))

  println("userID :-" + user.id)
  println("tweetID:-" + tweet.content)

Now, what happens when I used the concept of Java types to use more specific classes for the user ID and username? This means that, now, I can’t use any number directly and can’t mix a tweet ID with a user ID because the compiler is helping us to verify that. So, that is why we created four classes here to wrap around our very simple Int and String values. So, User and Tweet takes tiny types instead of Int or String values directly.

Let’s generate a bytecode for User.scala with the command:
javap -p User

public class User implements scala.Product,scala.Serializable {
private final UserId id;
private final Username name;

Now, if you look at the bytecode that is generated by this as we would expect, we would see the user has two fields, and those fields are the type UserId and UserName, which means that every time I create a User, I’m also creating instances of those two classes, as well. This is where Value classes come into the picture.

Let’s go through the one last example where we are using value  classes:

case class UserId(id: Int) extends AnyVal

case class Username(name: String) extends AnyVal

case class TweetId(id: Int) extends AnyVal

case class TweetContent(content: String) extends AnyVal

case class User(id: UserId, name: Username)

case class Tweet(id: TweetId, content: TweetContent)

object Test extends App {
  val user = User(UserId(1), Username("kunal"))
  val tweet = Tweet(TweetId(10), TweetContent("ABC"))

  println(s"userID :- ${user.id}")
  println(s"tweetID:- ${tweet.content}")

What we have done on the above example is we just took those tiny types and made them value classes by extending  AnyVal. They are perfect candidates because they all wrap around a single simple value. So, the four classes that we created just changed that into Value classes. But when you look into the bytecode, which is generated this time, you will get the difference.

public class User implements scala.Product,scala.Serializable {
private final int id;
private final java.lang.String name;

The above code is self-descriptive, so I am hoping that you are now well aware of value classes, where, and how to use them. Happy coding!

This post was originally published on the Knoldus blog

java ,value classes ,value ,tutorial ,username ,user

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}