3 ms·
I Haven't used java in ages. Though from a quick search, it's still just scalar/unary values. Rhough one of the better implementations of those. But the big
by ongy 3y ago
I Haven't used java in ages.
Though from a quick search, it's still just scalar/unary values.
Rhough one of the better implementations of those.
But the big advantage of the more sum type Style enums rust provides is the ability to nest values in them while preserving type safety guarantees.
So I still see them as miles better as a language concept.
- fifticon 3y agoerh no, those in java allow you to do just that. It is one of my favorite features of java. In essence, you get to embed multiple synchronized maps inside a java enum (if you want to). All handled 'invisibly' for you.
- Ygg2 3y agoStill, you get to see all fields from all variants, while Rust variants are more isolated.
- Sharlin 3y agoNo, Java enums can contain data but do so in a manner orthogonal to Rust enums. Java enums are not sum types; each variant is simply a (`final`) instance of the enum type which, mostly, is just a regular class type with a private constructor so that no other instances can be created. All variants have the same shape and the author of the enum decides what data the variants contain. Rust enums are sum types, which means that each variant can have a totally different shape and contain different data, and it's the user of the enum that supplies the data when they create an instance of a variant. This quintessential use case for sum types not possible with Java enums (although it is now sort of possible with records and sealed traits): enum Result<T, E> { Ok(T), Err(E) }
- papercrane 3y agoJava enums are a class with a fixed number of instances. The thing in Java that is closest to Rust enum's would be sealed classes, which was a preview feature in Java 15 and finalized and released with Java 17. https://openjdk.org/jeps/409 https://openjdk.org/jeps/409
- pjmlp 3y agoStill, better than C, C++ and C#, which was my point. For the real deal, there are sealed classes now, modeled on how Scala does it.