4 ms·
Probably with a composite class I guess. So a union type of types A and B has members of types A and B, and a non-nullable flag to indicate which one this insta
by tomtheelder 5y ago
Probably with a composite class I guess. So a union type of types A and B has members of types A and B, and a non-nullable flag to indicate which one this instance is. Intersection type is just the same thing without the flag.
I don't write Java, though, just guessing.
- Someone 5y agoYou can also implement an union type as a sealed interface/abstract class with two classes that implement/extend it (https://openjdk.java.net/jeps/409 https://openjdk.java.net/jeps/409, https://www.baeldung.com/java-sealed-classes-interfaces https://www.baeldung.com/java-sealed-classes-interfaces)
- mumblemumble 5y agoIt's one option. It has the advantage of structurally limiting the types that can be used in that spot. It has the disadvantage (compared to true union types) of offering no static help beyond that. If you add a case, for example, you're 100% on your own to make sure that all code that interacts with the type is updated to handle the new case. Slip-ups will produce run-time errors rather than static ones. It's also rather tricky (and awkward) to set things up such that consumers are forced to check the case value before attempting to coerce it. All of this can be worked around with custom linter rules, but then that becomes its own maintenance burden. My preference is to try and invert things such that you can rely on dynamic dispatch and "tell, don't ask." That eliminates the need to coerce things at run-time in the first place.