> Am 14.6.2016 um 21:53 schrieb Levi Morrison <le...@php.net>: > >> I'm personally against Union types because it makes no sense for classes > > I've been over this before but I'll repeat it here for completeness: > this is not true. Unions provide a way to discriminate between > potential sets of types. Even among classes there is power in unions. > Consider the idea of encoding a Something or Nothing with methods such > as `map`, `flatmap`, `filter`, etc. > > A Something will return a Something for map, and a Nothing will return > a Nothing. By using inheritance there are two problems: > > 1. We can create additional subclasses that do not obey the > semantics of the type. Imagine how frustrating a stack that does not > behave like a stack would be; same principle here. > 2. We don't have covariant return types so we cannot express that > Nothing::map will return Nothing and Something::map will return > Something. > > Using two final classes for Something and Nothing and then doing a > union on them has neither of these downsides. Even if we add return > type covariance we cannot solve problem 1. > > Given that there are numerous other uses with built-in types such as > Array | Traversable (iterable), int | string (array key), int | float > (numeric) and so forth it does not make sense to me to special case > these things. Generality is better for language features than special > casing.
What Levi tries to explain: unions are like a temporary virtual super-interface to any accepted class without actually being implemented by them. Typically you are writing adapters for these things, but an adapter is not always the solution (i.e. in cases where a part of the handling is identical, but depending on the actual class (instanceof) they ultimately get dispatched to somewhere else). For exactly these cases (which, I admit, aren’t numerous [The cases where it’s legitimate and there is no other superior solution]) union classes are helpful. Bob