scala学習----コリー化

3753 ワード

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"))