switch on Class ?
forax at univ-mlv.fr
forax at univ-mlv.fr
Sun Aug 23 21:16:23 UTC 2020
> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "Remi Forax" <forax at univ-mlv.fr>, "amber-spec-experts"
> <amber-spec-experts at openjdk.java.net>
> Envoyé: Dimanche 23 Août 2020 17:40:05
> Objet: Re: switch on Class ?
> It has indeed come up before. There is some overlap with pattern switch, and
> some non-overlap, but it's pretty clear the impact of pattern switch is much
> larger.
> I would much prefer to finish the discussions on the fundamentals first, which
> are actually blocking progress on a much-higher-priority feature. So let's come
> back to this later.
> I also have reason to believe that, if we do generalized patterns property, we
> won't need to do this as a language feature, we can do it as a library feature.
> So, let's come back to this later.
Exhaustiveness is hard to emulate in a library.
Rémi
> On 8/23/2020 11:25 AM, Remi Forax wrote:
>> There is a feature of Pizza (remember Generic Java ++) we have not discussed
>> yet,
>> being able to do a switch on Class.
>> public sealed interface Numeric<T extends Numeric<T>>
>> permits Amount, Percentage, Quantity {
>> private BigDecimal value() {
>> return switch(this) {
>> case Amount(value) -> value;
>> case Percentage(value) -> value;
>> case Quantity(value) -> value;
>> };
>> }
>> private static <T extends Numeric<T>> T fromValue(Class<T> type, BigDecimal
>> newValue) {
>> return type.cast(switch(type) {
>> case Amount.class -> new Amount(newValue);
>> case Percentage.class -> new Percentage(newValue);
>> case Quantity.class -> new Quantity(newValue);
>> });
>> }
>> default T add(T numeric) { return fromValue(getClass(),
>> value().add(numeric.value())); }
>> }
>> with Amount be declared like this
>> record Amount(BigDecimal value) implements Numeric<Amount> { }
>> This kind of switch is interesting because it's also one that can be exhaustive,
>> like the switch on type or the switch on Enum.
>> In the method fromValue, type is typed as a Class<T> so a Class<? extends
>> Numeric<...>> and given that Numeric is a sealed class only permitting Amount,
>> Percentage and Quantity, the only possible Class for a switch(type) are
>> Amount.class, Percentage.class and Quantity.class.
>> I'm pretty sure the call fromValue(getClass(), ...) doesn't not compile because
>> the compiler has no idea that all subtypes of Numeric implements
>> Numeric<themselves> but you get the idea.
>> regards,
>> Rémi
More information about the amber-spec-observers
mailing list