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.
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.
Matched with GeeksForGeeks
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.
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 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.
hashCodecannot 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.
- Scala Extractors
- Scala | Partially Applied functions
- Scala Keywords
- Scala Iterator addString() method with example
- Scala | Functions Call-by-Name
- Parameterless Method in Scala
- Introduction to Scala
- Scala | Decision Making (if, if-else, Nested if-else, if-else if)
- Scala | Loops(while, do..while, for, nested loops)
- Scala | Closures
- Scala Iterator size() method with example
- Scala Iterator slice() method with example
- Scala | Pattern Matching
- Scala | Functions - Basics
- Scala Varargs
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.