public static void test(Foo f) {
if (f isinstanceof SubA) {
SubA a = (SubA)f;
/* ... */
} else if (f isinstanceof SubB) {
SubB b = (SubB)f;
}
}
This works okay but you have to implement all the machinery yourself, and for a statically typed language Java is notoriously type-unsafe so if you make a mistake with your casts you're basically not going to find out until you get an exception at runtime. And of course there might be other existing subclasses of `Foo` which means that you get no compile-time guarantee that you didn't miss a possible case.Standard ML approaches subtyping in a very different way that renders this kind of approach impossible. It gives you less freedom in that it eliminates downcasting, but that ultimately results in a safer language. Of course Standard ML has proper sum types with all of their compile-time guarantees so there's little reason for it anyway.
public static void test(MaybeFoo mf) {
switch(mf.type) {
case MaybeFoo.NOTHING:
/* ... */
break;
case MaybeFoo.JUST:
Foo f = mf.getFoo();
/* ... */
break;
}
}
Still has exhaustiveness checking and no downcasts. Still can throw if you use the wrong get* under one of those branches, so I'm certainly not saying it's ideal, but I think it legitimately expresses a sum type and can be implemented in most any language with small adjustments.I would note that when I'm dealing with tagged unions in C, as soon as the operation gets at all complicated (more than maybe 3 lines?) I try to pass it off to another function operating on the internal value which restores safety outside the boilerplate. I agree that support for a true tagged union is ideal, though. (Actually, this might make a good attribute in GCC...)
(I could totally be missing/misunderstanding something, though...)
So that's the blindness. The pre/post conditions around how mf.type relates to its surroundings cannot be expressed first-class in the code. You are required to do risky things like call potentially partial code.
(a -> r) -> r -> Maybe a -> r
means you only access the `a` if it's there and the access/matching are inextricably linked.So, I think "bare primitive types lack meaning" is basically correct given that you interpret "meaning" as "meaningful uses/actions".