How to declare a function parameter to receive the functions you have selected?

I defined a function in Kotlin:

fun convertExceptionToEmpty(requestFunc: () -> List<Widget>): Stream<Widget> { try { return requestFunc().stream() } catch (th: Throwable) { // Log the exception... return Stream.empty() } } 

I defined a Java method with this signature:

 List<Widget> getStaticWidgets() throws IOException; 

I try to compose them like this:

 Stream<Widget> widgets = convertExceptionToEmpty(() -> getStaticWidgets()) 

When compiling, I get this error:

Error: (ln, col) java: unregistered exception java.io.IOException; must be caught or declared abandoned

How to determine the parameters of my function to accept the function that throws?

+7
java lambda java-8 throws kotlin
source share
2 answers

The problem is that Java checked for exceptions , but Kotlin does not. The requestFunc () -> List<Widget> parameter type will be mapped to the function interface Function0 <List <Widget "> , but the invoke statement does not throw a checked exception in the Kotlin code.

Thus, you cannot call getStaticWidgets() in a lambda expression since it throws an IOException , which is a checked exception in Java.

Since you manage Kotlin and Java code, the easiest solution is to change the type of the parameter () -> List<Widget> to Callable<List<Widget>> , for example:

 // change the parameter type to `Callable` ---v fun convertExceptionToEmpty(requestFunc: Callable<List<Widget>>): Stream<Widget> { try { // v--- get the `List<Widget>` from `Callable` return requestFunc.call().stream() } catch (th: Throwable) { return Stream.empty() } } 

Then you can use the method reference expression in Java8, for example:

 Stream<Widget> widgets = convertExceptionToEmpty(this::getStaticWidgets); //OR if `getStaticWidgets` is static `T` is the class belong to // v Stream<Widget> widgets = convertExceptionToEmpty(T::getStaticWidgets); 
+4
source share

I am afraid that you cannot do anything, but to catch this exception:

  Stream<Integer> widgets = convertExceptionToEmpty(() -> { try { return getStaticWidgets(); } catch (IOException e) { e.printStackTrace(); } return null; }); 
0
source share

All Articles