Diamond in type patterns?

forax at univ-mlv.fr forax at univ-mlv.fr
Thu Jan 7 21:51:53 UTC 2021


----- Mail original -----
> De: "Florian Weimer" <fw at deneb.enyo.de>
> À: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>, "Brian Goetz" <brian.goetz at oracle.com>, "Amber Expert
> Group Observers" <amber-spec-observers at openjdk.java.net>
> Envoyé: Lundi 4 Janvier 2021 23:24:01
> Objet: Re: Diamond in type patterns?

> * Remi Forax:
> 
>> Should we allow the diamond syntax in a cast ?
> 
> I think it would be particularly useful for lambdas.  E.g. if Java
> gains a parallel set of function interfaces that can throw IOException
> (translating it to UncheckedIOException for the implemented
> traditional functional interfaces), one could write
> 
>  (IOSupplier<>) () -> Files.newBufferedReader(path)
> 
> to obtain an IOSupplier<BufferedReader> that is also a
> Supplier<BufferedReader>.
> 
> Without the cast, one would have to add convience functions
> 
>    static <T> IOSupplier<T> of(IOSupplier<T> supplier) {
>        return supplier;
>    }
> 
> and write:
> 
>  IOSupplier.of(() -> Files.newBufferedReader(path))
> 
> But maybe that's good enough.

The problem is that usually this kind of cast are better done by specifying the type argument,
i.e. instead of
  List.of((IOSupplier<>) () -> Files.newBufferedReader(path))
it's better to write
  List.<IOSupplier<>>of(() -> Files.newBufferedReader(path))

so it also means that type arguments should be able to use the diamond syntax.

and BTW, the convenience function is
  @SuppressWarnings("unchecked")
  static <T> IOSupplier<T> of(IOSupplier<? extends T> supplier) {
    return (IOSupplier<T>) supplier;
  }  
with a wildcard because this is the way to encode the fact that a IOSupplier is always covariant at least until we add variance declaration at declaration site.

I tried to convince Brian to add those methods in java.util.function interfaces, but fail.

Rémi


More information about the amber-spec-experts mailing list