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

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.

主站蜘蛛池模板: 麻阳| 安达市| 凉城县| 莒南县| 桓仁| 山东省| 嘉鱼县| 屏南县| 宝山区| 吴川市| 公主岭市| 梅州市| 虹口区| 磐安县| 叙永县| 巩留县| 百色市| 洞口县| 合阳县| 鸡西市| 定边县| 古蔺县| 灵石县| 长岭县| 临湘市| 日土县| 莲花县| 西丰县| 东山县| 莆田市| 新巴尔虎左旗| 岳阳县| 绿春县| 天台县| 周至县| 阿克苏市| 霍邱县| 五华县| 伊金霍洛旗| 奉贤区| 赞皇县|