Reputation: 2892
While going through Programming in Scala, i came across:
While you can define your own value classes (see Section 11.4), there are nine value classes built into Scala: Byte, Short, Char, Int, Long, Float, Double, Boolean, and Unit. The first eight of these correspond to Java's primitive types, and their values are represented at run time as Java's primitive values. The instances of these classes are all written as literals in Scala. For example, 42 is an instance of Int, 'x' is an instance of Char, and false an instance ofBoolean. You cannot create instances of these classes using new. This is enforced by the "trick" that value classes are all defined to be both abstract and final.
Due to which new Int
gives the error class Int is abstract; cannot be instantiated
val a: Int = new Int
in Scala. Java allows new Integer(23)
.
Question: What is the trick
the author is taking about. Why Scala defines value classes
to be abstract and final
.
Upvotes: 1
Views: 1764
Reputation: 262524
What is the trick the author is taking about ?
The "trick" is that
new
).So as a result, value classes cannot be instantiated by application code.
Why Scala defines value classes to be abstract and final.
The point of value classes is that they are defined by their (immutable) value/contents. The object identity is not relevant.
The Scala compiler also tries to optimize value classes by not creating any objects at all where possible (just using unboxed primitives directly). That only works if we can be sure that you can just box and unbox at will.
In Java new Integer(1)
and another new Integer(1)
are two different objects, but that is not useful for a pure value class (if you want to use these different instances as lock monitor objects or something else where you need object identity, you are just confusing yourself and others and should not have used Integer
).
Upvotes: 2