Java tagged union / sum types : <p>Is there any way to define a sum type in Java? Java seems to naturally support product types directly, and I thought enums might allow it to support sum types, and inheritance looks like maybe it could do it, but there is at least one case I can't resolve.
To elaborate, a sum type is a type which can have exactly one of a set of different types, like a tagged union in C.
In my case, I'm trying to implement haskell's Either type in Java:</p>

<pre><code>data Either a b = Left a | Right b
</code></pre>

<p>but at the base level I'm having to implement it as a product type, and just ignore one of its fields:</p>

<pre><code>public class Either&lt;L,R&gt;
{
    private L left = null;
    private R right = null;

    public static &lt;L,R&gt; Either&lt;L,R&gt; right(R right)
    {
        return new Either&lt;&gt;(null, right);
    }

    public static &lt;L,R&gt; Either&lt;L,R&gt; left(L left)
    {
        return new Either&lt;&gt;(left, null);
    }

    private Either(L left, R right) throws IllegalArgumentException
    {
        this.left = left;
        this.right = right;
        if (left != null &amp;&amp; right != null)
        {
            throw new IllegalArgumentException("An Either cannot be created with two values");
        }
        if (left == right)
        {
            throw new IllegalArgumentException("An Either cannot be created without a value");
        }
    }

    .
    .
    .
}
</code></pre>

<p>I tried implementing this with inheritance, but I have to use a wildcard type parameter, or equivalent, which Java generics won't allow:</p>

<pre><code>public class Left&lt;L&gt; extends Either&lt;L,?&gt;
</code></pre>

<p>I haven't used Java's Enums much, but while they seem the next best candidate, I'm not hopeful.<br>
At this point, I think this might only be possible by type-casting <code>Object</code> values, which I would hope to avoid entirely, unless there's a way to do it once, safely, and be able to use that for all sum types.</p>
