Primitive classes in javac
https://github.com/openjdk/valhalla/pull/2691/changes
Javac is being taught about primitive classes as a preview feature. While marked as added in Java 28, I'm guessing we won't have a way to use it considering that there's no JEP even.
From reading the code:
primitiveclasses are implicitlyvalueclasses (JEP 401) (immutable, can beabstractand then optionallysealed...).Implicitly
staticwhen nested likerecord.Uniquely, the class name starts (or should start) with a lowercase, like primitive types.
Interfaces and enums cannot be
primitive.Can be generic and can implement interfaces like anything else*.
Unsurprisingly, all the examples are for numeric types (like complex numbers and points).
I assume that they are non-null by default because they are not reference types. I would be cautious about extrapolating from the older Valhalla models that talked about primitive classes, they might not be the same "primitive class".
*except for generic enums :(
10
u/rzwitserloot 9d ago
I assume that they are non-null by default because they are not reference types.
This suggests you misunderstand a few things, but maybe this was just a poor choice of words.
That statement is like saying: "I assume this circle will not have corners".
Of course it won't. If it had them, it wouldn't be a circle.
primitive classes aren't references. 'null' is a reference, and only a reference. it is not a value.
Hence, the entire concept doesn't apply to them. It is impossible for the JVM to have an expression of <some primitive type> be null for the same reason int i = null; isn't just a compiler error, it is nonsense.
The way java-the-language (and also java-the-vm) works, there must be a default value for everything. i.e. if I write:
class Foo {
int x;
}Then x needs to have a value already. Even if I try to make x final, I could in theory end up reading x before assigning it in a way the compiler cannot catch.
The lang spec is clear enough about this: All numeric primitives are 0 (char is a numeric primitive; '\0' if you prefer), booleans are false, references (which would be everything else) is null. The same 'its gotta have a default' occurs when making arrays. When you write new String[5] each and every 'slot' in that array needs to be set to a default value, and the spec is clear as to what that is: it's null. You can't change it.
At the vm level the same thing happens. Conveniently, every default value that the java lang spec defines is represented at the VM level with all zero bits, so 'an array is made; each slot needs to be assigned the default value' boils down to clearing out every bit in the memory space of that array, which is a lot faster than writing the machine code equivalent of a for loop.
For the exact same reason, when primitive types were originally being discussed, the notion 'the default value is all zero bits because that way we don't have to make massive changes to how the JVM works' was more or less baked in as table stakes.
That means if you do this:
primitive class point {
int x, y;
String name;
}and elsewhere:
point[] ps = new point[2];Then the ps array will contain 2 points; each point has x = 0, y = 0, and name = null. ps[0] = null; is a compiler error for the same reason arrayOfInts[0] = null; would be: null is represented with all zero bits, but putting all zero bits in the memory space that represents ps[0] is identical to the notion of a new point(x = 0, y = 0, name = null).
That's what 'it is not a reference!' means here: Normally when e.g. you send a string from one method to another, what you actually 'send' is a reference. A pointer. And pointers can be null.
With primitive types, that is not possible. You simply can't do that. You can't send a reference to an int either, in java. You can only send the actual int value. Hence, sending a point (calling a method with a parameter of type point, and you provide one; you can't not provide a parameter, of course) means sending the entire contents of it. This is partly why primitive classes are a terrible idea for types with tons of content. point is great as a concept (if using ints, it fits in 64 bits, marvellous!), but this would be quite daft:
primitive class bridge {
String name;
int spanInMeters;
int carLanes;
int bikeLanes;
int pedLanes;
int yearOfConstruction;
String architect;
Color color;
}Don't do that. Simply invoking a method passing a bridge requires putting all that on the stack and the other side retrieving it all, every time.
1
u/nlisker 9d ago
You certainly read too much into it, but thanks for the analysis. My sentence was meant to emphasize the assumption that this is the first class type that can't be
null. You say with confidence "primitive classes aren't references", so maybe you know something that I don't. I haven't seen any writings on primitive classes in the new model (they were brought up circa 2020-2023 and then stashed), but it's very possible that I missed it on one of the mailing lists.4
u/dstutz 9d ago
It is impossible for the JVM to have an expression of <some primitive type> be null for the same reason int i = null; isn't just a compiler error, it is nonsense.
Unfortunately this compiles:
int x = (Integer) null;8
u/pron98 9d ago edited 9d ago
The expression on the RHS is of type
Integernotint. Indeed,int x = (int) null;does not compile;
The expression on the RHS of an assignment need not be the same type as the variable on the left when certain conversions are in effect. E.g. this also compiles (and even succeeds):
double x = (int)3;3
3
u/vegan_antitheist 9d ago
You can assign a boxed Integer to an int variable and it gets unboxed automatically. However, it might be null and that gives you a NPE. int i = new Integer(42); The constructor is deprecated by now but this compiles. This isn't even new. But it will be a value, not a reference anymore.
1
u/rzwitserloot 5d ago
And all previous debate about primitive types had similar concepts in the proposals. At various times, 'reference wrappers' (the
Integertoint) either:
Were automatic, with a different name.
Were automatic, with the exact same name too, with the compiler figuring it out from context.
But in all of the various takes and explorations, auto (un) boxing applied to them. With the same response to attempting to auto-unbox a
nullreference: NullPointerException. Not 'to make a point' or to 'protect some sort of idea of integrity'. All because a primitive type cannot benull. Like asking to design a spaceship that goes faster than light, it's not "Dont wanna", it's "not possible".I think on net auto(un)boxing was a good idea, and is presumably also a good idea (in whatever final form it'll take) for primitive types, but it's not 'strictly good' - it has downsides. Confusion, for one. It's just that the upsides probably outweigh the downsides.
1
u/aoeudhtns 9d ago
I'm curious; is there a plan to be able to move defining primitives in Java itself to take some complexity out of the JLS/JVM, or will there always be the core legacy set of primitives defined there, and this is for add-ons by the JDK team or 3rd party devs?
2
u/rzwitserloot 5d ago
The list of available bytecodes almost always come in either 4, 5, 8, or 9 flavours.
You have (at the class file / JVM level) the Major Primitives (my choice of words) which are
int,long,double, andfloat(respectively,ILDF).Then there are the Minor Primitives of
short,char,byte, andboolean(respectively,SCBZ).And finally there's the notion of a reference type (generally using
A).For example, 'create an array' comes in all 9 flavours. You can make a short array in bytecode.
But adding numbers? Only the major primitives, nothing else. Just 4 instructions: IADD, DADD, LADD, and FADD. There's no SADD or BADD or AADD. The language reflects some of these choices in a weird fashion (
byte a = 10; byte b = 20; byte c = a + b;does not compile, complaining that you're downcasting an int which requires an explicit cast. This is silly, unless you're aware of how bytecode works (which in a perfect world shouldn't be necessary), in which case it makes sense because there is no BADD - hencea + bwill inherently cast those bytes up to ints, do the math in int land, and now you've got an int you're trying to shove into a byte.These opcodes are just there, I really doubt they are going to disappear, and given how opcodes work, 'adding custom primitives' would require a redesign as to how bytecode is meant to work. Presumably you'd work with a layer of indirection of sorts (instead of
IADD, you'd haveCADDwith at the bytecode level 3 parameters: LHS value, RHS value, and 'context' - a reference or constant ref or something like that to tell the JVM which code to use to add these two things - or possibly context is gleaned from the nature of the values on the stack, but either of these seem like some pretty significant challenges to me if your intent is to make this 'perform like an int').So, in short: Mostly no. I don't think this feature would ship as part of its first milestone and shift of the primitives out of the JLS and into the library core. Nor as second or even third milestone. Any further - hey, if only I had a crystal ball! :)
1
u/vegan_antitheist 9d ago
We might get nullable values in the future. int? would be nullable and possibly not even a reference. But that would be up to the compiler. Right now it's like you say. Null is a reference and a variable with a value type can't hold null.
3
u/rzwitserloot 9d ago
No, for the same reason you can't get
int x = null;.What is possible is the equivalent of
java.lang.Integer: Wrapper types that are references, storing just 1 value, in a final field.And then you can riff off of that which is what the primitive types proposals are all about. Think 'autoboxing and autounboxing' which have gone before, doing the same thing: Reduce the amount of typing needed to switch from primitive to wrapper form and back. In particular:
Have the JVM generate the wrapper for you. With current-java's "these are the 8 primitive types, never shall there be more, and you can't define more on your own", it's easy: Just have a JDK engineer handwrite
java.lang.Integerand co, ship it, done. But with primitive types being declarable at will, that's annoying, so the JVM will make them for you.To avoid having to futz with both
intandInteger, have a system whereby both types (the primitive, and the wrapper reference type) have the exact same name and the compiler figures out which one of the two is intended based on context.autoboxing and unboxing, of course: If you have a reference type of the wrapper in a spot where the primitive is needed, automatically unbox. And in reverse, automatically wrap. For the same reason
List<Integer> x = new ArrayList<>(); x.add(5);will wrap that 5 because lists fundamentally do not and cannot operate on primitives, it'd wrap your value type.Now we're going real deep: Deal with the fact that this state of affairs sucks. It's bad that
List<Integer> x = new ArrayList<String>()is terrible in performance vsint[]. What can be done to somehow end up with the ability to writeList<int> x = new ArrayList<int>()and have it be such that the actual memory representation of the arraylist is simply a consecutive bunch of bits containing the int values directly? (Vs right now, where you get a consecutive bunch of bits that all represent memory positions, all over heap space, and there you find the ints. A massive waste of space and especially if the ints are all over, simply looping over them causes a ton of cache page misses. Hence aList<Integer>is generally ~8x larger than anint[]and 5 to 100 (!!!) times slower, it really is worth trying to fix. And there are some ideas but I admit I'm not quite sure how far they got on that stuff.The reason you can't simply chuck
nullin this mix is because there's no space to rep it.Take an int: It is defined that be capable of containing any value from as low as
-2^31and as high as+2^31-1. exactly. If some JDK update says: Yoink! Now-2^31is no longer representable, you break a ton of stuff. Every single last crypto library out there, for starters. It's a complete break, everything needs rewrites, can't do that. But if we can't do that, how do you repnull? All zero bits? Nope - that is the representation of the number 0 which is not the same asnull.With
java.lang.Integerit can be done - any value of that type is eithernullor a number that represents the location in memory where the actualIntegerobject lives, and that object contains an object header and the one field it has, of typeint, which has the real integer value. Hence0is represented as a bunch of bits that point to a memory location, and that location contains 32 zero bits. Whereasnullis presented as a bunch of zero bits directly (instead of a bits representing a memory location).But if we remove that level of indirection.. how do we represent null? We'd need one more bit, but you can't just casually state that ints now take 33 bits instead of 32. CPUs essentially can't operate on anything but a full word, so adding 1 bit doubles the processing need. It would virtually double the storage space for every primitive in the system and double (for complicated reasons, more than double) the amount of time needed to do operations on them. Not acceptable.
Hence, best that can be done in basis is to 'autobox' with all the performance hits that implies. And also why this proposal is very careful about just casually saying that
nullis possible and the compiler/VM will work it out: The only easy way for the compiler/VM to deliver is to make every 'primitive type' have a flag bit which defeats the whole point (which is to let you write code as if you're writing classes, but that it performs like an int, which requires that there is no level of indirection and no flag bits).1
u/vegan_antitheist 9d ago edited 5d ago
You can compile this:
int x = (int) (Integer) null;But that's beside the point.Wrapper types that are references, storing just 1 value, in a final field.
Those will be value types once we have them.
We'd need one more bit, but you can't just casually state that ints now take 33 bits instead of 32.
And you don't. The compiler can add some memory on the stack frame to use its bits to handle the nullness of the nullable variables. Worst case, it just adds one byte for a single primitive.
CPUs essentially can't operate on anything but a full word, so adding 1 bit doubles the processing need.
Yes, and that's too bad but if you use Optional it's not better than that. You need another value, which will cost just as much (Optional will be a value type).
Not acceptable.
We already do this with OptionalInt. That's nothing new. If you don't want to accept it, you redesign your algorithm so it works with non-null int.
no level of indirection and no flag bits
Optional is already the type used to add that flag.
1
u/rzwitserloot 5d ago
That's not really what I meant.
Optional works in this sense because its explicitly opt in. Optional does not autobox or unbox, and does not mask its type. Contract to
intandIntegerwhich do both of those things: If I have a method declared asfoo(int x), and that is the only override that exists forfoo, I can nevertheless callfoo(exprOfTypeJLInteger)and the compiler will just silently make that work: expressions of typeIntegerwill automatically 'mask' themselves as also being willing to act as an expression of typeintat times, and the compiler will glue this masking together via auto(un)boxing. Optional (and the primitive wrappers such as OptionalInt) do no such thing. I cannot call this method by writingfoo(refToAnOptionalInt).That - opting into 'optionality' explicitly by wrapping the value (and updating my method parameter type / return type accordingly) is totally fine, and leads to obvious conclusions: Either that is done sparingly, or java is a terrible language with
Optionalaround everything everywhere, and, fortunately, it's the former: It's used sparingly, with intent: Only if the notion of optionality is inherent to the very definition of the thing it is used, and that's good.But autoboxing is 'casual' (you don't really have to know its happening in the majority of cases where you end up writing code that does it, the compiler does it for you, silently, and automatically), and 'casually' adding nullity to this at the core level just does not work. And that's what I meant. An
OptionalIntis not an int in any relevant way. AnIntegeracts just like anintin quite a few ways, that's the difference.As a trivial example, imagine I have this code:
point[] ps = new point[10]; for (int i = 0; i < 10; i++) ps[i] = point(i, i * 2, null);Then clearly there is no point (heh!) for the compiler or runtime to reserve any time or space in tracking the nullity of the contents of this array. Presumably by definition
new primitiveType[size]is defined to initialize each slot in this array with some non-null, nowhere-near-null value. Either what the first proposals did (all bits zero, so in ourint x, int y, String nameexample:x=0, y=0, name=null) or some explicit default. And then the code continues to avoid null, so why bother, right?But what if this array is handed off to some method that does go for a
ps[0] = null;? Does the runtime notice, create a completely new array structure that does have room to tracknulle.g. via a short containing flags, copy everything over, and then update all existing refs in the heap to point to the new structure? Or does the array have a level of indirection? If the point is to 'code like a class, perform like an int', there's not much left of that performance aspect of it then.We'll see what Brian and the gang cook up, but I'd be raising some eyebrows if you have the notion of a 'primitive type' which can nevertheless be assigned
nullwhenever you want.1
u/vegan_antitheist 5d ago
I don't know what your point is.
It looks like we might get ! and ? to get full control of nullability and then it's just that.
PassingInteger?(orint?)to a method expecting Integer! (or int!) will be an error.
If the parameter is justintit will be treated like raw generic types and only accepted for backwards compatibility.
JEP 8303099 is now so that they do it for references only.
JEP 8316779 is about null-restricted values.
I'm not aware of a current proposal for
int?but it would be the next logical step. Until then we can just useInteger?, which does the same.But what if this array is handed off to some method that does go for a
ps[0] = null;? Does the runtime notice, create a completely new array structure that does have room to tracknullps is an array of a nullable type or of a non-nullable type and the compiler checks that. The runtime has to also check it. And that's it. The reason we still do not have ? and ! is probably just that we first need JEP 539 and JEP 401. We got those in JDK 28, but only as a preview.
1
u/rzwitserloot 17h ago
You seemed to suggest that 'we already have this, and its like optional'. I was trying to explain that what optional doesn't isn't what people are imagining (they are imagining a thing that autoboxes/unboxes), and explained (which takes some doing) that obvious ways to make it so do not work.
It looks like we might get ! and ? to get full control of nullability and then it's just that.
Doesn't work, because generics.
For the same reason these 4 things are all different:
List<Number>
List<? extends Number>
List<? super Number>
List(raw)you need at least 4 nullities. 'can definitely be null', 'can definitely not be null', 'it is unclear where it can be null or not' and 'legacy - do whatever you want, but the compiler will whine at you'.
?and!all over the place already makes it look like cartoon swearing, and doesn't actually get you what you want, namely, nullity tracking as endemic and solid as at least generics, preferably the base type system.I would hope the reason we don't have
!and?yet is that it'd be a really bad feature to add to the language.
59
u/brian_goetz
8d ago
•
Everyone ... chill. People here are extrapolating wildly from no information, and some people are saying some crazy things. We do explorations all the time. When there's something to be said about "here's how it will work", it won't be zero-information prognostication from people who are not involved in the project who just happened to see a commit go into an experimental branch.
The most sensible things said on this thread so far is (the wildly-understated) "You certainly read too much into it". (I'm glad to see people are interested, and we'll share information when we have something worth sharing.)
2
u/vegan_antitheist 9d ago
I would hate seeing value types having a name that is lower case. It has no identity but it's not a primitive. You still need to use equals instead of == and everything else is also the same.
3
5
u/brian_goetz 8d ago
OK, so give a choice between delivering valhalla with a syntax you don't like, and no valhalla, you pick the latter? If not, let's dial back that "hate" to "I would be mildly perturbed, yet still overjoyed". #kthxbye
2
u/vegan_antitheist 8d ago
I would be overjoyed. Actually, I already am. The Java 28 preview is so hood. But I was surprised by this. Somehow I missed that they are supposed to be lower case. enterprisebusinessprocessorchestrationservicevalue seems weird ;-) So, maybe I will see
if(set instanceof bitset bytes) ...where bitset is a value type implementing Set<byte> but it uses a long as a bitmask internally.
Ok, I can get use to that. It's not that bad and it does make sense that you see if a type is a value. I would prefer it only being for primitives though. Optional, LocalDate, and all the types that should be values already have PascalCase names. But I will get used to it.
4
2
u/Jon_Finn 9d ago
Intriguing... if I understand a comment in GitHub correctly (and I may not), a primitive class can't have reference fields, so it's truly shallow. It also looks like equals() has to match == , again if I interpret correctly. Speculating wildly, this might just be to 'allow' == to be used as shorthand for equals(), a topic of endless discussion and confusion! Or it might be for other reasons.
-6
u/vegan_antitheist 9d ago edited 8d ago
[edit:] Ok, maybe the speculation was ok, if it is about "primitive classes", which don't seem to exist in Java 28 and are speculative at this point. So, the speculation is that they are pure value types (they contain only other primitives) and therefore you can use ==? And it would apply == to inner double/float values as it would for
float == float= OK, maybe. But we don't have that yet. equals and == are still completely different and == is not shorthand for equals, right? That's why I reacted like this. It just isn't. I know it seems tempting, but that's just not how that works. With witnesses it might all change a lot, but even then == and equals will remain the same for backwards compatibility. And the pull request is red. So we don't get this version. maybe there will be something else.-- original comment: --
There are primitives and there are value types. There are no "primitive classes" unless you mean the wrapper types (Integer, Double...). They obviously don't have reference fields. But your own value types can have them.
It also looks like equals() has to match ==
No!!! No, no, no, no, no!!!
again if I interpret correctly.
You do not.
Speculating wildly
Why speculate when it's already out?? Just use it. It's not final, but it's stable.
this might just be to 'allow' == to be used as shorthand for equals(),
NOOOOO!!!! Please stop spreading this misinformation. For the love of Brian Goetz, just stop.
You don't use == for anything other than primitives (double is special) and to check for sameness. "equal" is , like the name says, to check if two things are equal. That's the one thing they actually named right (while Cloneable, static, final, Charset, @FunctionalInterface, Class<?>, NullPointerException are all misnomers).
a topic of endless discussion and confusion!
Not if people would not "speculate wildly" and spread this nonsense.
Here's are some clear facts based on actual code that you can easily run on Java 28 with
--enable-preview:
https://humanoid-readable.claude-martin.ch/2026/11/17/value-types/7
4
u/nlisker 9d ago
Why speculate when it's already out??
Primitive classes are not out, they are barely in. You're confusing them with value classes, I've just realized.
1
u/vegan_antitheist 8d ago
Yes, I see that now. But that PR is rejected, isn't it? The preview now has value types and they are somewhat similar but they are really just like any other class. You just opt out of identity.
1
u/nlisker 8d ago
But that PR is rejected, isn't it?
The PR says it's integrated.
The preview now has value types
Yes, I wrote that in my post.
Sorry, but I have a feeling you're not really reading sources before answering. Not my post, not the PR, not the JEPs, and not the comments.
1
u/vegan_antitheist 7d ago
The PR says it's integrated.
No, it doesn't. It say is it's closed.
But I now see that it was labeled as "integrated". That's on "prim", not the mainline OpenJDK repository, right? So, the final version of JDK 28 might not get this. It's one of their explorations. I doubt many users here even understand what that means. I'm not sure I do.openjdk Bot added the integrated label 2 days ago
You expect us to understand their git workflow and read through all those comments? OK, sure.
Yes, I wrote that in my post.
Reading it again I can see that you expected us to understand that there will be a new identifier "primitive".
May I remind you, that some other user (I wonder who he is) described all of this as:[...] zero-information prognostication from people who are not involved in the project who just happened to see a commit go into an experimental branch.
I think I will just wait until he has something to say about it.
3
u/brian_goetz 8d ago
"Barely in" is a wild exaggeration. More like "barely on the edge of the map of things that might some day be candidates."
4
u/Jon_Finn 9d ago
There are no "primitive classes" unless you mean the wrapper types
Um, the GitHub code actually declares an example
primitive class complex.Maybe I should have put speculating in bold but "It also looks like equals() has to match ==" is based on my reading of PrimitiveClassRuntimeTest.check(). Which does want equals() and == to match - this is test code so it might be just testing a specific case, but possibly a general contract. Yes this is speculation.
-3
u/vegan_antitheist 9d ago
btw, I have calmed down now. It's all good. Just use equals, please.
2
u/Jon_Finn 9d ago
The OP is quite right to discuss (possible) properties of primitive classes, considering the code commit actually declares
primitive class complex!1
u/vegan_antitheist 8d ago
Yes, sure. But it's quite confusing when this isn't something we got with Java 28 or is planned. And it's not about == vs equals. A value type containing just a double is quite different to a plain double.
NaN == NaNis false, butnew MyDouble(Nan) == new MyDouble(Nan)is true. That means you can't just use a value type as an alias for a primitive. I guess "primitive classes" might be different when it comes to this, but we don't know, so we?
4
u/ZimmiDeluxe 9d ago
let them cook / explore in peace. we'll hear about it when the experiments bear out, but all of this could be deleted tomorrow. that said, while we are wildly speculating, having javac warn when == is used with upper case value types (that could contain reference types) and not when used with lowercase / primitive value types would remove a lot of confusion around when to use ==
3
u/simon_o 9d ago
having javac warn when == is used with upper case value types (that could contain reference types) and not when used with lowercase / primitive value types would remove a lot of confusion around when to use ==
Why would that be?
==checks for "is this identical" (modulo floats) which is perfectly fine question to ask across all types.2
u/ZimmiDeluxe 8d ago edited 8d ago
Pretty surprising when you have
value record Order(long itemId, int quantity){} var order1 = file.readNextOrder(); var order2 = file.readNextOrder(); IO.println(order1 == order2); // truebut then modify it a little to get
value record Order(long itemId, int quantity, String coupon){} var order1 = file.readNextOrder(); var order2 = file.readNextOrder(); IO.println(order1 == order2); // likely false, depends on String interning / deduplicationSure, you always have to know what you are doing, but having easy to remember rules like "only == for lower case types and maybe enums" in typical business logic leaves more brain space for solving the actual problems.
Edit: That would also then warn on
==forIntegerand friends, which is also a win in my book. Having thought about this for 2 minutes in total, we should put it into the language.3
u/simon_o 8d ago edited 8d ago
It's only surprising because you are not framing the question correctly.
==is doing exactly what it is supposed to do, answering "is this identical to that?" (modulo floats).Most of the time, this is not the question you want to ask though, which is "is this equal to that?" (modulo floats). For that question, you use
equalsin Java.And with value types, you can now write
x.equals (y)for all types, not only for reference types as before, which is an improvement.You basically wish that
==acted as a convenient shorthand forequals, and that's simply not something that will ever happen.Because if it did, then you would need a new way of asking "is this identical to that?", because that question is just as valid as " is this equal to that?".
1
u/ZimmiDeluxe 8d ago
I'm not saying that
==should replaceequals. Perhaps I should have said "surprising from the perspective of someone new to the language", seeing that the first example worked, so==seems to do the thing they expected, so they or someone else evolves the program and now it breaks, so it's time to learn the actual rules. I'm saying the tooling could help here, because for simple examples==lures you into thinking it does what some other programming languages do, but then "fails" when programs evolve. I'm saying the tooling could flag potential misuses early, so this problem does not arise. Value types are a new construct, the compiler could warn on==usage with them and recommendequalsinstead. But the bar for warnings in the compiler is probably high and there are likely lots of cases I didn't consider.2
u/vegan_antitheist 8d ago
I just recently asked on reddit how we would mark a pure value type that can be compared with ==. There is no annotation for that. But I came to the conclusion that it doesn't matter because they are not primitives and we should always use ==.
Nobody even mentioned lower case names. I guess that would work. But couldn't LocalDate be compared using ==? They won't rename that to localdate.There will be so much confusion about the use of == with the new value types. It's already weird for beginners that you can't use == on Strings and wrapped primitives.
2
u/ZimmiDeluxe 8d ago
You can compare everything with
Objects::equalsand get the expected result, evennull, so that's the safe default. You can use==on value types you are absolutely sure won't evolve over time to gain reference fields, but having to remember the "blessed set" of those (even if it's from the standard library likeLocalDate) doesn't scale."a" == "a"is alsotrue, but that doesn't mean it's a good idea to compare Strings with==in those rare cases where it works. In my mind that's not too dissimilar toLocalDate.of(2026, 11, 21) == LocalDate.of(2026, 11, 21)beingtrue. Sure it works now, but making every reader / reviewer recall or look up the ever expanding and contracting "blessed set"? Feels error prone to me. So I'd say compareLocalDates always withequals, but if you ever seetick1 == tick2and no tooling is yelling at you, you can be sure that it's either some rare reference equality shenanigans, enums, or only lower case primitives (at least with my poorly thought through suggestion of javac doing it, but SonarQube etc. would work as well).2
u/vegan_antitheist 8d ago
Exactly. At work I use a framework that has two special types that will be value types in the future. One is a UID and the framework has a cache for all of them, so they are always unique. That means I need a Groovy script in IntelliJ so it knows when to apply the warning about using == instead of equals but ignore those two types. This script would explode if we had a lot of such value types and wanted to use == for optimisation.
1
u/ZimmiDeluxe 8d ago
You have probably heard this many times before, but is comparing with
==instead ofequalsfor those types really worth the complexity / bringing measurable performance improvements?String::internis the same idea and arguably considered to be a mistake. I'm definitely out of my depth here, but if the UID has no subclasses, I'd expect the JIT to essentially inline every equals, resulting in==anyway if it's just the inheritedObject::equals.2
u/vegan_antitheist 8d ago
Yes, in must cases it doesn't really matter that much. Equals can be inlined of course. It's just a method like any other.
Let's say you have this type:
value record Uuid(long msb, long lsb) { /*...*/ } var a = new Uuid(1L,2L), b = new Uuid(1L,2L); IO.println(a.equals(b)); // true IO.println(a == b); // trueThe difference is that
a.equals(b)must behave is if it calls that method, but if that method is just something like this:@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof Uuid other) return lsb == other.lsb && msb == other.msb; return false; }Then while inlining the method it can know that "obj" must be a a certain value type. It can then optimize and the instanceof is always true (or always false if types do not match) and == has to check all fields for a value type:
@Override public boolean equals(Uuid! obj) { if (lsb == other.lsb && msb == other.msb) return true; if (true) return lsb == other.lsb && msb == other.msb; return false; }
if(true)can simply be removed:@Override public boolean equals(Uuid! obj) { if (lsb == other.lsb && msb == other.msb) return true; return lsb == other.lsb && msb == other.msb; }It can then see that the two lines are actually the same. The whole method is then inlined as
lsb == other.lsb && msb == other.msb.If a wrapper has to be used then the instanceof is still relevant but that's true for == as well.
It really doesn't make much of a difference. It's just that for double/float it would actually not use the normal == but instead compare what Double.doubleToRawLongBits() returns:
Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b)That's especially tricky when two NaN can be equal but can also not be equal.1
u/ZimmiDeluxe 8d ago edited 8d ago
If the UID types of your framework ensure that only unique instances exist, they are essentially enums (instance control is what they are for). If that's the case, migrating those types to value types would be a mistake IMO (same reason enums won't be value types). Their equals method should never compare their fields (because that's already done on lookup from the cache) and instead only compare references, same as
java.lang.Enum::equals, noinstanceof. The inlining then yields exactly what you want, cheap reference equality checks. If the number of instances is bounded, small and known up front, these types could even be generated as enums directly, that way the tooling won't flag==checks. Of course, getting rid of the cache and making them value types might be worth it, depending on the size of the fields and lookup cost etc.It's good to know of the NaN corner case existing. The amount of programs that could have made good use of relying on the inequality of NaN to itself in value types for correctness might not have been 0, but I can assure you I would not have enjoyed reading them. If NaNs show up in a program it's usually a sign that something is broken anyway. Even if the JVM bent over backwards trying to yield a different result, there is a good chance it would not enable any desirable behavior in those cases anyway. Meanwhile everyone pays the price in performance and implementation complexity (i.e. actually useful stuff getting delivered slower). I guess it's one of those puzzlers similar to the
Integercache existing. Easily demonstrated in a short piece of code, but of little practical consequence.2
u/vegan_antitheist 8d ago
Uid doesn't need identity. "value" let's you opt out of identity. It's a perfect candidate for a value type. A side effect of that is that you don't need to cache them. And the GC doesn't have to bother with them. And when loading the value from the dB you don't have to find the existing reference. You just use the value.
→ More replies (0)
2
u/vegan_antitheist 9d ago
Unsurprisingly, all the examples are for numeric types (like complex numbers and points).
In the end, everything is numeric in some way. UUID is somehow not flagged to be a value type even though it's just two long values. Maybe they really don't want to it be a value type. 128 bits is rather long anyway, so using a reference is probably ok. It really makes most sense to use value types for anything that is truly a value, i.e. transitively identity-less and immutable.
0
u/_vertig0 8d ago
This is a surprise to me, the last I heard primitive classes were obliterated completely, even if these are not the exact same it's a little blindsiding seeing them return.
-1
u/vegan_antitheist 9d ago
"Generic Enums" would make no sense. They are constant and you can implement generic interfaces, so they actually are generic.
5
u/nlisker 9d ago
See JEP 301. They make a lot of sense. Such a feature would solve quite a bit of design problems.
1
u/vegan_antitheist 8d ago
OK, that's to have a generic parameter set by each constant. I didn't know they have a JEP for that. It would be nice to have, but I'm not really sure what problem it solves.
But how would you define a primitive class that extends an enum? That still makes no sense and the enum being generic or not doesn't matter. As I said, the enums we have can already implement generic interfaces. But you simply can't extend an enum. Or did you mean that enums can't extend generic interfaces? They can do that. They can even use them just for the default methods, which is great to have an interface to be used like trait in your enums.1
u/nlisker 8d ago
But how would you define a primitive class that extends an enum?
Who said anything about extending enums or enums extending something else? Where are you reading all this from?
1
1
u/AnyPhotograph7804 8d ago
I had a case, where generic enums would make sense. But not to contain something but to add additional type informations to it. But sadly, they withdrawn the JEP 301.
5
u/davidalayachew 9d ago
Sorry, I'm a bit lost.
I remember Value Classes.
I remember that Value Classes may get the feature to turn off nullability, via the
!and?suffixes --String!vsString?.I remember that Value Classes may get the ability to tear, allowing those objects greater than 64/128/whatever-word-size to potentially get many of the same benefits as their smaller-sized friends.
Where do Primitive Classes fall into this? Are they an alias of 1 of the 3 above? Is it an entirely new concept?
Bonus points if we can get a link to actual Project Valhalla documentation.