- 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.
- C語言程序設(shè)計案例教程
- Apache Oozie Essentials
- Mastering Entity Framework
- Python爬蟲開發(fā)與項目實戰(zhàn)
- Mastering Scientific Computing with R
- QGIS By Example
- Kotlin從基礎(chǔ)到實戰(zhàn)
- 響應式架構(gòu):消息模式Actor實現(xiàn)與Scala、Akka應用集成
- Android驅(qū)動開發(fā)權(quán)威指南
- 區(qū)塊鏈架構(gòu)之美:從比特幣、以太坊、超級賬本看區(qū)塊鏈架構(gòu)設(shè)計
- Java 9 with JShell
- Android編程權(quán)威指南(第4版)
- Python面試通關(guān)寶典
- Java Web動態(tài)網(wǎng)站開發(fā)(第2版·微課版)
- Java核心編程