【问题标题】:How do I declare a function parameter to accept functions that throw?如何声明函数参数以接受抛出的函数?
【发布时间】:2017-08-24 14:42:50
【问题描述】:

我在 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())

编译时出现此错误:

错误:(ln, col) java: 未报告的异常 java.io.IOException;必须被抓住或宣布被扔掉

如何定义我的函数参数以接受抛出的函数?

【问题讨论】:

  • 您可以尝试注释您的 convertExceptionToEmpty 函数以抛出 IOException,这可能会绕过此错误。
  • @piwo,我认为这不会有帮助,异常来自 getStaticWidgets() 方法

标签: java lambda java-8 kotlin throws


【解决方案1】:

问题是 Java 有 checked exceptions 而 Kotlin 没有。 requestFunc 参数类型() -&gt; List&lt;Widget&gt; 将映射到功能接口Function0<List<Widget>> 但运算符invoke 在Kotlin 代码中不会抛出已检查异常。

因此,您不能在 lambda 表达式中调用 getStaticWidgets(),因为它会引发 IOException,这是 Java 中的已检查异常。

由于您同时控制 Kotlin 和 Java 代码,因此最简单的解决方案是将参数类型 () -&gt; List&lt;Widget&gt; 更改为 Callable&lt;List&lt;Widget&gt;&gt;,例如:

// 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);

【讨论】:

    【解决方案2】:

    恐怕你只能抓住那个异常:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 2012-07-11
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多