Thought on multiplicity of properties in Java

Martin Desruisseaux martin.desruisseaux at geomatys.com
Tue Sep 18 08:16:27 UTC 2018


Hello Rémi

Le 18/09/2018 à 00:28, forax at univ-mlv.fr a écrit :

> - theoretically, the covariance is defined in term of sub-typing,
> trying to widen it's definition may have unintended consequences that
> need studying.
>
Agree that it would require studying. But we have a general guidance,
which is that a subtype must obey to all constraints declared in the
parent type. The Java type covariance follow that rule: we can use a
more specific return type in a subclass, but not the converse since it
would broke the constraint defined by the return type in the parent
class. The proposed "multiplicity covariance" follows the same rule: a
subclass would be allowed to define a more specific multiplicity, but
the converse is not allowed. For example a [0…1] multiplicity defined in
the parent class can be restricted to the [1…1] multiplicity in a
subclass, but can not be changed to [0…2] or any other value outside the
[0…1] range.


> - technically, we can implement whatever conversions we want because
> the "convariance conversion" is implemented using brige, but we may
> not implement that the "covariance conversion" using bridges in the
> future if by example we do some kind of reification of the type
> arguments, so this may hamper the possible futures of Java.
>
The proposed "multiplicity covariance conversion" would be implemented
using bridges too. However I admit that I lack knowledge on the
consequences in a context of reification.


> - the conversion from Optional to a List is not a conversion already
> defined by the JLS, this need also to be specified because there is no
> reason to limit this conversion to only the covariance case, by
> example if you have an Optional<String> named opt, this statement
> List<String> list = opt; should compile. This means that you have to
> formally defines the conversion and perhaps the reverse conversion
> too, Optional<String> opt2 = (Optional<String>)list; at that point you
> are not backward compatible with the current JLS because this code
> currently always throws a CCE.
>
In the "multiplicity covariance" proposal, the set of conversions that
are allowed is determined by the above-cited rule that multiplicity in
return value can only be restricted - not widened. By labelling Foo =
[1…1], Optional<Foo> = [0…1] and Collection<Foo> = [0…∞], we can build
the set of allowed conversions. Those conversions would not be performed
by casts, but by bridge methods (in widening direction because the
bridge methods implement the methods defined by parent class):

  * [0…1] ← [1…1]: Optional.of(value);
  * [0…∞] ← [1…1]: List.of(value);
  * [0…∞] ← [0…1]: if empty Collections.emptyList() otherwise
    List.of(value);

Martin




More information about the core-libs-dev mailing list