3

I try to compile this code in android studio:

public class Test {
    public void test() {
        java.util.Optional.of(12).orElseThrow(RuntimeException::new);
    }
}

It requires to handle Throwable.

But signature of this method is next:

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X 

I extract Optional.class from android.jar in Android/Sdk/platforms/android-27 and decompile it with android studio. It has wrong signature:

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws Throwable

What I do wrong?

Thank you.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • What is your problem? That you have to handle exception using this code? – Mershel Dec 10 '18 at 09:44
  • Problem that this code requires to handle Throwable (catch or declare 'throws'). But I throw runtime exception and it must compiles without any changes. – Michael Orlov Dec 10 '18 at 09:50
  • Try using com.annimon.stream.Optional instead – Mershel Dec 10 '18 at 10:03
  • 3
    I use streams in my project and their return java.util.Optional – Michael Orlov Dec 10 '18 at 10:06
  • Could you live with using the no-arg `orElseThrow`? It throws a `NoSuchElementException`, a subclass of `RuntimeException`, so doesn’t require you to catch or declare. Im case your API level is not high enough, the `get` method provides the same functionality. – Ole V.V. Dec 10 '18 at 10:20
  • I try to copypaste source class Optional to my project and use it for my example. This works well. I don't know why android sdk provides Optional.class with wrong signature. – Michael Orlov Dec 10 '18 at 10:25
  • Is this the same class that you're referring to https://developer.android.com/reference/java/util/Optional.html#orElseThrow(java.util.function.Supplier%3C?%20extends%20X%3E) ? – Naman Dec 10 '18 at 10:39
  • Yes it's the same: android studio has option 'download sources'. – Michael Orlov Dec 10 '18 at 11:01
  • @MichaelOrlov You've definitely mixed up something here `public T orElseThrow(Supplier extends X> exceptionSupplier) throws Throwable ` wouldn't even compile if you notice the standalone `T` there. Maybe an incorrect jar? – Naman Dec 10 '18 at 12:32
  • @nullpointer it's compiled. It makes me think that this Optional.class compiled from another source file :) android.jar downloads from android studio automatically. I tried to re-download it, but it doesn't affect. – Michael Orlov Dec 10 '18 at 13:10

1 Answers1

0

If you need to use java.util.Optional try this way:

if(!java.util.Optional.of(12).isPresent()){
     throw new RuntimeException();
}
Mershel
  • 542
  • 1
  • 9
  • 17
  • 1
    It's bad, because I have too many places when I need this construction. Creating method for this is bad too because we lose readability if stream chain is so large. – Michael Orlov Dec 10 '18 at 10:20