Conditional methods "for free"

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Tue Dec 16 11:22:15 UTC 2014


This is indeed a clever way to restrict applicability of certain methods 
to specific receivers. However, applicability is only half of the story 
here; the other half is membership. In your proposed solution, 'or' will 
be a member of Optional - regardless of the parameterization of the 
generic class. It seems likely that the feature we are after (not saying 
we have yet arrived to a full solution here) will also restrict 
membership - i.e. 'or' will simply not exist on an Optional<String> (and 
then applicability would of course follow). When  migrating legacy, 
erasure-based code, it is in fact fairly common to end up with cases in 
which existing methods (Collection.remove(Object) anyone?) no longer 
make sense in a fully any-fied world - and it is likely we will need a 
way that to say that those method are only members of certain receivers 
but not others.

That said, stay tuned, as you'll soon hear more about this ;-)

Maurizio

On 16/12/14 02:41, Tomas Mikula wrote:
> On Sep 30, 2014, at 8:10 AM, Simon Ochsenreither <simon at
> ochsenreither.de> wrote:
>
>>    There was a short mention of "conditional methods", e.g. enabling
>>    methods only for a subset of some generic type.
> I don't know where conditional methods were mentioned and what their
> current state is (any links?), but here is an idea how to get
> conditional methods "for free" on top of two other (missing) features,
> which would both be useful independently in their own right.
>
> The first feature is lower bounds on type parameters, i.e. <U super T>, as in
>
>      class Optional<T> {
>          public <U super T> Optional<U> or(Optional<? extends U> other);
>      }
>
> The other one is to allow multiple type paramater bounds, even if one
> of the bounds is itself a type variable. That is, allow bounds like <U
> extends T & Foo> or <U extends Foo super T>.
>
> I have no idea how technically feasible these features are, but I have
> encountered use cases for both of them.
>
> Once we have lower bounds and multiple bounds, we can express
> conditional methods like this:
>
>      class Optional<T> {
>          default <I extends Integer super T> int getAsInt() {
>              I value = get();
>              return value.intValue();
>          }
>      }
>
> Valid substitute for I exists only when T extends Integer, thus the
> getAsInt() method can effectively be invoked only on
> Optional<Integer>.
>
> Regards,
> Tomas




More information about the valhalla-dev mailing list