4

I have a this very simple line of code that is not compiling on 1.8.0_74

Collections.singleton(Optional.of("").orElseThrow(RuntimeException::new));

Compiler error is:

Collections.singleton(Optional.of("").orElseThrow(RuntimeException::new)); ^ where X,T are type-variables: X extends Throwable declared in method orElseThrow(Supplier) T extends Object declared in class Optional

On the other hand it compiles fine when you break it to separate lines:

String some = Optional.of("").orElseThrow(RuntimeException::new);
Collections.singleton(some);
kubagruszka
  • 211
  • 2
  • 11
  • Does this work by any chance? ImmutableSet.of(Optional.of(new String()).orElseThrow(() -> new RuntimeException())).orElseThrow(() -> new RuntimeException()); I have a feeling it's complaining as you're not throwing the exception up the chain, that's an example, though I'm sure there are better ways to pass the exception on then what I've done – Draken Apr 01 '16 at 07:21
  • What happens if you make the first version `Optional.of(new String())...`? – chrylis -cautiouslyoptimistic- Apr 01 '16 at 07:27
  • @Draken nope in your proposed code is wrong. The method `orElseThrow()` returns the specific type `String` and it's being set of one element of `String` in this case, so you can't do again `orElseThrow()` on the set object. – kubagruszka Apr 01 '16 at 07:27
  • @chrylis nope this type hint doesn't help and it's still not compiling. – kubagruszka Apr 01 '16 at 07:29
  • 1
    See http://stackoverflow.com/questions/25523375/java8-lambdas-and-exceptions – chrylis -cautiouslyoptimistic- Apr 01 '16 at 07:29
  • Yes @chrylis this looks like my question is a duplicate then. Sadly that they put resolve on java 9... Anyway I will download pre release and see what comes out. Thanks! – kubagruszka Apr 01 '16 at 07:33
  • 1
    If I understand correctly, it will be [backported to 8u92](https://bugs.openjdk.java.net/browse/JDK-8142883). – Tagir Valeev Apr 01 '16 at 07:45
  • I do confirm this is compiling fine on **jdk-9-ea+111** – kubagruszka Apr 01 '16 at 07:45
  • 1
    Nice (almost) self-contained example. You could get rid of the 3rd party library reference by replacing `ImmutableSet.of` with `Collections.singleton`. And you can simplify the example by replacing `new String()` with `""` and `() -> new RuntimeException()` with `RuntimeException::new`… – Holger Apr 01 '16 at 08:19
  • Thanks @Holger that was a good catch – kubagruszka Apr 01 '16 at 08:41
  • Another interesting fact related to this issue is that eclipse (4.5.2) internal compiler compiles this code smoothly :-) – kubagruszka Apr 01 '16 at 09:22
  • I've just checked with lately released 8u92 and I do confirm it works fine now ! – kubagruszka Apr 25 '16 at 12:59

0 Answers0