Conditional methods "for free"

Ali Ebrahimi ali.ebrahimi1781 at gmail.com
Tue Dec 16 08:28:35 UTC 2014


see
http://mail.openjdk.java.net/pipermail/lambda-dev/2010-November/002646.html
for history.

On Tue, Dec 16, 2014 at 6:11 AM, Tomas Mikula <tomas.mikula at gmail.com>
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