scala学习----柯里化

1、鸭子类型,走起来像鸭子,叫起来像鸭子,就是鸭子。函数中使用{ def close(): Unit }作为参数类型,因此任何含有此函数的类都可以作为参数传递。好处是不必使用继承特性。

 def withClose(closeAble: { def close(): Unit },
op: { def close(): Unit } => Unit) {
try {
op(closeAble)
} finally {
closeAble.close()
}
} class Connection {
def close() = println("close Connection")
} val conn: Connection = new Connection()
withClose(conn, conn =>
println("do something with Connection"))

2、柯里化技术(currying)def add(x: Int, y: Int) = x + y 是普通函数 def add(x: Int) = (y:Int) => x + y 柯里化后的结果。相当于返回一个匿名函数。def add(x: Int)  (y:Int) => x + y 是简写。这就是柯里化。柯里化让我们构造出更像原生语言提供的功能的代码。

 def withClose(closeAble: { def close(): Unit })
(op: { def close(): Unit } => Unit) {
try {
op(closeAble)
} finally {
closeAble.close()
}
} class Connection {
def close() = println("close Connection")
} val conn: Connection = new Connection()
withClose(conn)(conn =>
println("do something with Connection"))
上一篇:VCC、VDD、VEE、VSS


下一篇:perl常见符号