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

  • Learn Scala Programming
  • Slava Schmidt
  • 190字
  • 2021-06-10 19:35:51

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.

主站蜘蛛池模板: 甘孜| 汉中市| 府谷县| 宁国市| 襄垣县| 平湖市| 邯郸县| 曲靖市| 竹溪县| 邵武市| 阳原县| 宜宾县| 荃湾区| 金川县| 含山县| 普安县| 嘉定区| 娱乐| 平远县| 互助| 瑞安市| 晴隆县| 永登县| 清苑县| 洮南市| 龙门县| 长顺县| 利津县| 南部县| 合水县| 卢湾区| 安达市| 陵川县| 军事| 张北县| 车险| 涿州市| 吉木萨尔县| 都江堰市| 库尔勒市| 丹巴县|