r/java • • Mar 17 '21

JEP 401: Primitive Objects (Preview)

https://openjdk.java.net/jeps/401?preview=true
174 Upvotes

49 comments sorted by

View all comments

37

u/Hall_of_Famer Mar 18 '21

I love the fact that I don’t have to deal with the distinction between objects and primitive values in languages such as C# and Kotlin ‘cause everything is an object including primitive values. This JEP is amazing, a great move for the next version of Java.

1

u/cre_ker Mar 18 '21

Well you have to because in C# value types are objects but they have value semantics and mutable. Every time you assign them to something you make a copy. This JEP essentially proposes the same thing but objects are immutable. I’m not sure about that. Seems much more limiting and, depending on implementation, might require tons of copying like with any immutability simply because you have to allocate another instance on every mutation.

0

u/x4u Mar 18 '21 edited Mar 18 '21

I agree with you, making value types immutable on the language level seems like a odd decision to me as well. I understand why it makes sense internally, but it would have been possible to emulate mutability to make it appear as if they were mutable on the language level. The point is that it's not impossible to mutate value types by assigning a newly constructed value, but this just leads to more boilerplate code, may be less efficient than what a (future) compiler could do, is less readable and thus more error prone. It's also a additional arbitrary inconsistency in the language that now some types are mutable and others are not.

Edit: as this gets downvoted without comment, I'll include a code example...

primitive class Point
{
    int x;
    int y;
}

Point center = new Point( 3, 4 );
center.x = 4;      // not possible because immutable
center = new Point( 4, center.y ); // legal

The last two lines are the same operation but the more intuitive variant is not allowed while the more cumbersome line is. It would have been possible to allow mutability on the language level by compiling the upper line exactly as if it were written like the lower one.

3

u/Hangman4358 Mar 20 '21 edited Mar 20 '21
Point center = new Point(3, 4);
Point otherCenter = center;
center.x = 4;

What is otherCenter.x?

Before primitive classes you expect that center and otherCenter are the same object. You also expect that after assigning x on center, otherCenter.x will also return 4.

Making assignment of members syntactic sugar for creating a new instance for primitive classes means you need to know what type of class Point is. Now the effect of the assignment will have on otherCenter.x is dependent on the type of class Point is.

The whole point (no pun intended) is to make is so you don't need to know. That from a programmers perspective they act the same. So making the classes immutable means that you have to be explicit when objects change.

1

u/elastic_psychiatrist Mar 20 '21

Brilliant explanation, thank you.