On variance-based subtyping for parametric types

By Atsushi Igarashi and Mirko Viroli

Abstract

Abstract. We develop the mechanism of variant parametric types, inspired by structural virtual types by Thorup and Torgersen, as a means to enhance synergy between parametric and inclusive polymorphism in object-oriented languages. Variant parametric types are used to control both subtyping between different instantiations of one generic class and the visibility of their fields and methods. On one hand, one parametric class can be used as either covariant, contravariant, or bivariant by attaching a variance annotation—which can be either +,-, or *, respectively—to a type argument. On the other hand, the type system prohibits certain method/field accesses through variant parametric types, when those accesses can otherwise make the program unsafe. By exploiting variant parametric types, a programmer can write generic code abstractions working on a wide range of parametric types in a safe way. For instance, a method that only reads the elements of a container of strings can be easily modified so that it can accept containers of any subtype of string. The theoretical issues are studied by extending Featherweight GJ—an existing core calculus for Java with generics—with variant parametric types. By exploiting the intuitive connection to bounded existential types, we develop a sound type system for the extended calculus.