r/java • • 3d ago

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:

  • primitive classes are implicitly value classes (JEP 401) (immutable, can be abstract and then optionally sealed...).
  • Implicitly static when nested like record.
  • 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 :(

58 Upvotes

63 comments sorted by

4

u/davidalayachew 2d 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! vs String?.
  • 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.

4

u/nlisker 2d ago

They are a type of value class (all primitive classes are value classes). I haven't seen any documentation on them except for what's in the code, but I might have missed it in the mailing lists.

From the little I can see, they are not reference types, so can't be null (like they have ! implicitly). In all the examples in the code, they hold only primitive fields, so possibly they can't hold references at all, which would also make equals and == exactly the same, unlike for value classes.

4

u/Jon_Finn 2d ago

which would also make equals and == exactly the same, unlike for value classes.

Unless you override equals. But maybe you're not allowed to?? (speculation!)

1

u/nlisker 2d ago

¯\(ツ)/¯

0

u/vegan_antitheist 2d ago

NaN == NaN is false, but new MyDouble(Nan) == new MyDouble(Nan) is true, assuming MyDouble is a value type in Java 28. Just as new Double(Double.NaN) == new Double(Double.NaN) was always true (constructors are now deprecated). Maybe a "primitive class" containing a double (or multiple) would be different and it would have to compare them like a primitive double. I don't know if that makes sense. It's confusing as it is. I don't get what "primitive types" would even be used for. We now have value types as a preview and they work well. I don't understand why anyone would want custom primitives or what that would even be used for.

1

u/Duck_Devs 2d ago

The deprecated constructors still produce unique instances. Your example with the Double constructor has always been false.

3

u/vegan_antitheist 2d ago

Yes, I used the constructors here because I think most people think that "new" creates a new reference. But they do not really create instances in this case. The Java 28 code for java.lang.Double looks like this:

@jdk.internal.ValueBased
// See doc/value-class-preview.md for an overview of value class generation
public final /*value*/ class Double extends Number

So, it is a value type. That's a bit confusing because now we have "primitive double" and "value type Double". The latter is a wrapper for double, but it's also without identity. The primitive double is special, because NaN == NaN is false. new ... == new ... used to be just false because references of newly created objects can't be the same. This changes with Valhalla, because we use new to create values. With Java 28 and --enable-preview it's now like this:

void main() {
  IO.println(Double.NaN == Double.NaN); // false
  IO.println(new Double(Double.NaN) == new Double(Double.NaN)); // true
  IO.println(Double.valueOf(Double.NaN) == Double.valueOf(Double.NaN)); // true
  IO.println(Double.NaN == Double.valueOf(Double.NaN)); // false
  IO.println(Double.valueOf(Double.NaN) == Double.NaN); // false
}

This used to be all false. Try it yourself with Java 28:

java --enable-preview Main.java

2

u/Duck_Devs 2d ago

You said, verbatim, “Just as [code sample] was always true” about a code sample that is true only in preview. In current release builds, it is false. In all previous versions, it was false.

1

u/vegan_antitheist 2d ago

Yes, I was too. We just got the preview in Java 28 and we got value classes. this is about something that wasn't merged and is "barely on the edge of the map of things that might some day be candidates."

8

u/rzwitserloot 2d 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 2d 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 2d 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 2d ago edited 2d ago

The expression on the RHS is of type Integer not int. 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;

1

u/__konrad 2d ago

java.lang.NullPointerException: (...) because "null" is null

3

u/vegan_antitheist 2d 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/aoeudhtns 2d 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?

1

u/vegan_antitheist 2d 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 2d 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.Integer and 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 int and Integer, 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 vs int[]. What can be done to somehow end up with the ability to write List<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 a List<Integer> is generally ~8x larger than an int[] 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 null in 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^31 and as high as +2^31-1. exactly. If some JDK update says: Yoink! Now -2^31 is 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 rep null? All zero bits? Nope - that is the representation of the number 0 which is not the same as null.

With java.lang.Integer it can be done - any value of that type is either null or a number that represents the location in memory where the actual Integer object lives, and that object contains an object header and the one field it has, of type int, which has the real integer value. Hence 0 is represented as a bunch of bits that point to a memory location, and that location contains 32 zero bits. Whereas null is 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 null is 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 2d 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. Wurst 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.

47

u/brian_goetz 2d ago • Heartwarming

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.)

3

u/Jon_Finn 2d 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 2d ago edited 2d 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

u/nlisker 2d ago

There are primitives and there are value types. There are no "primitive classes"

Then what did the PR I linked do? And what is all of my post about?

4

u/nlisker 2d 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 2d 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 2d 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 1d 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 2d ago

"Barely in" is a wild exaggeration. More like "barely on the edge of the map of things that might some day be candidates."

5

u/Jon_Finn 2d 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 2d ago

btw, I have calmed down now. It's all good. Just use equals, please.

3

u/Jon_Finn 2d 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 2d 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 == NaN is false, but new 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?

2

u/vegan_antitheist 2d 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

u/nlisker 2d ago

Why do you say that it's not a primitive? The JLS hasn't been updated for this feature yet as far as I'm aware (and I'm not very aware). The definition of what a primitive is can be expanded. Also, it looks like equals and == are exactly the same for primitive classes.

1

u/simon_o 2d ago

Also, it looks like equals and == are exactly the same for primitive classes.

How would that work for floats, or types that contain floats?

5

u/brian_goetz 2d 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 2d 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

u/Lizz_may0 2d ago

Primitive like monkeys? With coffee?

1

u/_vertig0 1d 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.

2

u/nlisker 1d ago

It's an experiment, they are not returning in the mainline.

1

u/_vertig0 1d ago

Oh. Well that's embarrassing on my part.

4

u/ZimmiDeluxe 2d 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 ==

2

u/simon_o 2d 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 2d ago edited 2d 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); // true

but 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 / deduplication

Sure, 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 == for Integer and 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.

2

u/vegan_antitheist 2d 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 2d ago

You can compare everything with Objects::equals and get the expected result, even null, 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 like LocalDate) doesn't scale. "a" == "a" is also true, 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 to LocalDate.of(2026, 11, 21) == LocalDate.of(2026, 11, 21) being true. 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 compare LocalDates always with equals, but if you ever see tick1 == tick2 and 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 2d 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 2d ago

You have probably heard this many times before, but is comparing with == instead of equals for those types really worth the complexity / bringing measurable performance improvements? String::intern is 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 inherited Object::equals.

2

u/vegan_antitheist 2d 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); // true

The 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 2d ago edited 2d 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, no instanceof. 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 Integer cache existing. Easily demonstrated in a short piece of code, but of little practical consequence.

2

u/vegan_antitheist 2d 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

1

u/vytah 1d ago

But couldn't LocalDate be compared using ==?

One downside of using == with built-in value types is that it makes it harder to change the code to make it compatible with pre-Valhalla Java.

2

u/simon_o 2d ago edited 2d 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 equals in 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 for equals, 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 2d ago

I'm not saying that == should replace equals. 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 recommend equals instead. 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 2d 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.

-1

u/vegan_antitheist 2d ago

"Generic Enums" would make no sense. They are constant and you can implement generic interfaces, so they actually are generic.

5

u/nlisker 2d 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 2d 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 2d 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

u/AnyPhotograph7804 2d 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.