Union and Intersection Types [feature request]

Basic language features like Tuples or Union and Intersection types open new approaches to solve the same problems.

It’s hard to provide convincing cases for, technically speaking, you could achieve the same without them, but it’s hardly the point.

Integer|ParseError parseInt(String value) is a much better contract than Integer parseInt(String value) throws ParseException.

The compiler will force you to handle it. Ideally it will allow you to call methods that, in this case, are in the intersection of the Integer and ParseError types, if any, without further checking.

It could infer variable types in logical branches, so that the following would be allowed:

Integer|String variable = ...
if (variable is Integer) {
    variable++
} else {
    variable = variable + "a"
}

Also, methods could accept intersection types to reduce usage of overloading, and you could also allow contra-variant overriding of interface methods. As an example, in most languages the following is allowed:

interface ObjectSupplier {
    Object supply()
}

class StringSupplier implements ObjectSupplier {
    @Override
    String supply() {
         ...
    }
}

Now, we could allow something like:

interface StringConsumer {
     void accept(String value)
}

class ObjectConsumer implements StringConsumer {
     @Override
     void accept(Object value) {
         ...
     }
}

and also

class ObjectOrStringConsumer implements StringConsumer {
     @Override
     void accept(String|Object value) {
         ...
     }
}
2 Likes