DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Trending

  • DGS GraphQL and Spring Boot
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Measuring the Impact of AI on Software Engineering Productivity
  1. DZone
  2. Coding
  3. Languages
  4. What Is a Value Class in Scala?

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.

By 
Kunal Sethi user avatar
Kunal Sethi
·
Updated Oct. 25, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
19.9K Views

Join the DZone community and get the full member experience.

Join For Free

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 Int, Boolean,  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. 

Scala (programming language)

Published at DZone with permission of Kunal Sethi, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: