我在Kotlin中定义了一个函数:
fun convertExceptionToEmpty(requestFunc: () -> List<Widget>): Stream<Widget> {
try {
return requestFunc().stream()
} catch (th: Throwable) {
// Log the exception...
return Stream.empty()
}
}
我已经使用此签名定义了一个Java方法:
List<Widget> getStaticWidgets() throws IOException;
我试图像这样组成它们:
Stream<Widget> widgets = convertExceptionToEmpty(() -> getStaticWidgets())
当我编译时,我收到此错误:
Error:(ln,col) java: unreported exception java.io.IOException; must be caught or declared to be thrown
如何定义我的函数参数以接受抛出的函数?
解决方法
问题是Java有
checked exceptions但Kotlin没有. requestFunc参数type() – >列表与LT;窗口小部件>将映射到功能接口
Function0<List<Widget>>,但运算符
invoke不会在Kotlin代码中抛出已检查的异常.
因此,您无法在lambda表达式中调用getStaticWidgets(),因为它会抛出IOException,这是Java中的已检查异常.
由于您同时控制Kotlin和Java代码,最简单的解决方案是更改参数类型() – >列表与LT;窗口小部件>至Callable< List< Widget>>,例如:
// 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()
}
}
然后,您可以在Java8中进一步使用方法引用表达式,例如:
Stream<Widget> widgets = convertExceptionToEmpty(this::getStaticWidgets); //OR if `getStaticWidgets` is static `T` is the class belong to // v Stream<Widget> widgets = convertExceptionToEmpty(T::getStaticWidgets);