scala学习----柯里化
1、鸭子类型,走起来像鸭子,叫起来像鸭子,就是鸭子。函数中使用{ def close(): Unit }作为参数类型,因此任何含有此函数的类都可以作为参数传递。好处是不必使用继承特性。
1 def withClose(closeAble: { def close(): Unit }, 2 op: { def close(): Unit } => Unit) { 3 try { 4 op(closeAble) 5 } finally { 6 closeAble.close() 7 } 8 } 9 10 class Connection { 11 def close() = println("close Connection") 12 } 13 14 val conn: Connection = new Connection() 15 withClose(conn, conn => 16 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 是简写。这就是柯里化。柯里化让我们构造出更像原生语言提供的功能的代码。
1 def withClose(closeAble: { def close(): Unit }) 2 (op: { def close(): Unit } => Unit) { 3 try { 4 op(closeAble) 5 } finally { 6 closeAble.close() 7 } 8 } 9 10 class Connection { 11 def close() = println("close Connection") 12 } 13 14 val conn: Connection = new Connection() 15 withClose(conn)(conn => 16 println("do something with Connection"))