scala - 不清楚 "Checked exception"中的 "functional programming in Scala"解释

标签 scala functional-programming higher-order-functions checked-exceptions

在《Functional programming in Scala》一书中,有这样一段话讲到“checked exception”:

Checked exceptions

Java’s checked exceptions at least force a decision about whether to handle or reraise an error, but they result in significant boilerplate for callers. More importantly, they don’t work for higher-order functions, which can’t possibly be aware of the specific exceptions that could be raised by their arguments. For example, consider the map function we defined for List:

def map[A,B](l: List[A])(f: A => B): List[B]

This function is clearly useful, highly generic, and at odds with the use of checked exceptions — we can’t have a version of map for every single checked exception that could possibly be thrown by f. Even if we wanted to do this, how would map even know what exceptions were possible? This is why generic code, even in Java, so often resorts to using RuntimeException or some common checked Exception type.

这部分我读了好几遍,但仍然不清楚为什么已检查的异常不适用于高阶函数

谁能举一些例子使它更清楚?

最佳答案

尝试编写函数map<A, B>在 java 。在某些时候,您会发现自己需要调用映射函数。您的映射函数可以是任何 并抛出它喜欢的任何类型的异常。函数map不能在其签名中包含映射器可能抛出的所有可能异常,因为它不知道它是什么。不可能写出 map 的类型签名有检查异常。

假设 map 的签名类似于 Colletion<B> map<A, B>(Function<A,B>, Collection<A>) .现在假设我们称它为 map(x -> throw new IOException, Lists.of(1,2,3)) .自 IOException被选中,它应该出现在map的签名中但直到你调用map ,它不知道它可以抛出这种类型的异常。

关于scala - 不清楚 "Checked exception"中的 "functional programming in Scala"解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402608/

相关文章:

java - Eclipse Java 中的 Scala 对象嵌套类

python - 不使用类时使用映射或类似方法更新字典

c - 该函数执行什么操作?

Javascript _.map() 与 array.map();为什么一个在这里工作而不是另一个?

php - 在 PHP 中转置多维数组

scala - 为什么cats在评估Reader时返回 `Id[T]`?

scala - 将主题映射回 Spark LDA 中的文档

scala - 如何评估 Scala 宏中的表达式?

haskell - 我可以基于 Bool 函数调用重载 Haskell 函数吗?

arrays - Julia:函数式编程:根据另一个值数组验证数组条目