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 short <(x: Short): Boolean
- Scala short <(x: Char): Boolean
- Scala Extractors
- Scala | Partially Applied functions
- Scala String indexOf(String str) method with example
- Scala String contentEquals() method with example
- Scala Keywords
- Scala Int /(x: Int) method with example
- Scala Int /(x: Short) method with example
- Program to print Java Set of characters in Scala
- Scala Map size() method with example
- Scala SortedMap addString() method with a start, a separator and an end with example
- Scala Iterator addString() method with example
- Scala String substring(int beginIndex, int endIndex) method with example
- Scala | Functions Call-by-Name
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.