by jez · 5y ago · 0 comments
> The throws clause is the only point in the entire Java language that allows union types. You can tack “throws A,B,C” onto a method signature meaning it might throw A or B or C, but outside of the throws clause you cannot say “type A or B or C” in Java.
In languages with better support for ad hoc union types, I think both the need and desire for checked exceptions fades. I wrote a little bit more about how two translate between the two concepts and what the benefits of using ad hoc union types are in this post in a blog post[2], but my point is that having a proper, fully fledged type system feature that composes with all other features of the type system is what drives most of the headaches away.
[1]: https://james-iry.blogspot.com/2012/02/checked-exceptions-mi...
Child castToChild(Object x) {
return (Child)x;
}
So at least it's not expensive from the standpoint of "uses more memory."Maybe you're saying that it's more expensive because dynamic dispatch on a type like (A | B) will be slower than static dispatch on a type like A, but most languages lacking ad hoc union types will already have other ways to do dynamic dispatch (parent classes, interfaces, etc.) so it's not like adding ad hoc union types solely incentivizes people to write slower, dynamically dispatched code.
Maybe when you say "performance" you mean that the performance of the type checker is slower? That's definitely true—as ad hoc union types get larger (dozens, hundreds, heaven forbid thousands of variants) the type checker will definitely struggle.
That being said, there have been some impressive optimizations in practice to speed these up (I've spoken with members of the TypeScript team touting some really cool improvements to their union types, and I've seen members of my team submit similar but not quite as good improvements to the union types in Sorbet for Ruby). So I definitely agree that a priori, they're going to be slower to type check, but I think that they can be made fast in common cases, and their benefit in terms of power added to the type system is just a really, really good tradeoff.
So I'm not sure I agree on face value that adding ad hoc union types to a language necessarily come with a performance expense.
class B extends UnionBase;
public UnionBase someMethod();
furthermore, UnionBase might have isA() and isB() if need be.
So, strictly speaking, your statement is incorrect.
public (A | B) someMethod();
in Java.I also want my tools to know what's being returned, as well as my compiler.
Usually these are the languages with more focus on type safety, like OCaml, Haskell and Rust.