Say that you have some different classes that does not really have any functionality in common, but somewhere in your program, you need one of them (which one is not necessarily important) because they have a functionality in that context. What is the best way to do that?
I know that you can take an Object
and use instanceof
to check whether it is one of those types, but I am looking for a way to let the type system ensure that it will just be one of those types. Or is that impractical/impossible?
What I thought about doing was to create an empty interface and implement it in all the classes that needed it. but I have seen that you are supposed to use annotations instead of a marker interface, but I am not sure if that applies in this situation because I do not really care about run-time information. Another thing I am worried about is that implementing that interface in those classes will cause spaghetti code. Those classes should not really have to know anything about how they are used elsewhere.
Best Answer
Here's a barebones generic implementation for two alternatives:
You box up objects of one of two types into an
Either
and then usematch
to call a function based on which type the boxed object has. The combination of a private constructor andfinal
inner subclasses ensuresOptionA
andOptionB
are the only possible subclasses ofEither
, so unless you start messing around with casting, if you get your hands on anEither<Integer, String>
you know it can only contain anInteger
or aString
.It should be fairly straightforward to:
boolean hasA()
orA getA() throws NoSuchElementException()
for times whenmatch
would be too verbose.interface
with two methods instead of two individualFunction
s (but theFunction
s are more concise if you use lambdas)Left
/Right
orFirst
/Second
instead ofA
/B
).equals
,hashCode
, and all that stuff.null
-checking.See also How do you encode Algebraic Data Types in a C#- or Java-like language?.