官术网_书友最值得收藏!

Extending functions

Nothing prevents a developer from extending a FunctionN trait the same way it is done with PartialFunction, though it seldom makes sense because of the limitations imposed by the referential transparency constraint. This means that such an implementation of the function should not have a shared state, nor should it mutate state. 

It might be tempting, for example, to implement a loaner pattern as a function, so that a used resource would be automatically closed after function application, but it won't be referentially transparent and thus won't satisfy the requirements for a function.

Here is how the implementation could look:

class Loan[-T <: AutoCloseable, +R](app: T => R) extends (T => R) {
override def apply(t: T): R = try app(t) finally t.close()
}

And this is what happens if we call it:

scala> new Loan((_: java.io.BufferedReader).readLine())(Console.in)
res13: String = Hello

scala> [error] (run-main-0) java.io.IOException: Stream Closed
[error] java.io.IOException: Stream Closed
[error] at java.io.FileInputStream.read0(Native Method)
[error] at java.io.FileInputStream.read(FileInputStream.java:207)
[error] at jline.internal.NonBlockingInputStream.read(NonBlockingInputStream.java:245)
...

Unfortunately, it is not even possible to test whether the second call would produce the same result (obviously it will not) because we broke the REPL by closing the Console.in.

主站蜘蛛池模板: 西青区| 彰化市| 正安县| 谷城县| 稻城县| 三都| 东港市| 竹北市| 财经| 长海县| 霞浦县| 青冈县| 兰西县| 宜兴市| 穆棱市| 清原| 驻马店市| 丹巴县| 微山县| 临西县| 贵港市| 教育| 新乐市| 鄂托克旗| 夏津县| 大埔县| 喀喇沁旗| 水城县| 西藏| 彭阳县| 增城市| 中宁县| 永善县| 黔西县| 澎湖县| 年辖:市辖区| 洪湖市| 苏尼特左旗| 依安县| 上蔡县| 汤原县|