Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type hint in method reference lambda results in raw type

Tags:

java

types

jvm

Mapping an Optional with an explicitly typed generic method reference seem to cause type inference to fail in some cases. In the following example the first line compiles whereas when giving the List::of-method an explicit type with List::<String>of it does not compile:

Optional.of("one,two").map(List::of).get().get(0).split(",");
// No problem, type inference works fine

Optional.of("one,two").map(List::<String>of).get().get(0).split(",");
// Compiler error, because the mapped Optional becomes typed with a raw List parameter (Optional<List>)

In the above case the type hint to List::of was unnecessary, but there are many cases where it is needed and to help the compiler one has to type hint the map, resulting in the much more verbose

Optional.of("one,two").<List<String>>map(List::of).get().get(0).split(",");

One case would be if we had some Either type like

static class Either<L, R> {
  L left;
  R right;

  private Either(final L left, final R right) {
    this.left = left;
    this.right = right;
  }

  static <L, R> Either<L, R> left(final L l) {
    return new Either<>(l, null);
  }

  static <L, R> Either<L, R> right(final R r) {
    return new Either<>(null, r);
  }
}

then

final String right =
    Optional.of("one,two")
        .map(Either::<String, String>left)
        .orElse(Either.right("three,four"))
        .right;

fails to compile, instead one has to do

final String right =
    Optional.of("one,two")
        .<Either<String, String>>map(Either::left)
        .orElse(Either.right("three,four"))
        .right;

Why is it so and are there any plans to change this?

Update:

I am using OpenJDK 15, but this seems to be a problem in Intellij - running javac from the command-line all of this compiles, but Intellij erroneously highlights some of the above lines as compile errors. I will close and report a bug.

like image 866
Andreas Berheim Brudin Avatar asked Feb 23 '26 15:02

Andreas Berheim Brudin


1 Answers

This turned out to be a bug in Intellij.

https://youtrack.jetbrains.com/issue/IDEA-252839

like image 180
Andreas Berheim Brudin Avatar answered Feb 26 '26 06:02

Andreas Berheim Brudin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!