首先是經常使用的匿名函數app
BNF描述以下函數
Expr ::= (Bindings | [‘implicit’] id | ‘_’) ‘=>’ Expr ResultExpr ::= (Bindings | ([‘implicit’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block Bindings ::= ‘(’ Binding {‘,’ Binding} ‘)’ Binding ::= (id | ‘_’) [‘:’ Type]
常見使用方式以下測試
x => x //只有一個參數,而且結果是這個參數自身 f => g => x => f(g(x)) //科裏化的匿名函數 //非匿名的寫法 def curry(f:AnyRef => AnyRef)(g:AnyRef=>AnyRef)(x:AnyRef):AnyRef = f(g(x)) (x: Int,y: Int) => x + y //最經常使用的形式 () => { count += 1; count } //參數列表爲空,使用一個非局部的變量count,加1後返回 _=>5 //忽略全部參數,直接返回定值
接着是模式匹配匿名函數scala
BNF描述以下code
BlockExpr ::= ‘{’ CaseClauses ‘}’ CaseClauses ::= CaseClause {CaseClause} CaseClause ::= ‘case’ Pattern [Guard] ‘=>’ Block
常見使用方式以下ip
scala.PartialFunction[S, T] { def apply(x: S): T = x match { case p1 =>b1 ... case pn =>bn } def isDefinedAt(x: S): Boolean = { case p1 => true ... case pn => true case _ => false } } //這是scala中PartialFunction 實現方式 def scalarProduct(xs: Array[Double], ys: Array[Double]) = (0.0 /: (xs zip ys)) { case (a, (b, c)) => a + b * c } 其中case的內容,至關於下面的匿名函數 (x, y) => (x, y) match { case (a, (b, c)) => a + b * c }
下面的代碼是我本身些的一段測試ci
class Sample { println("You are constructing an instance of Sample") } object Sample { def foo(a: Int)(f:(Int,Int) => Int): Int = { f(a,3) } def foo2(a: Int)(f:(Int)=>Int):Int = { f(3) } def main(args: Array[String]) = { new Sample val n = (a:Int,c:Int) => { println(a) a * c } val b = foo(2) _ val m = b(n) println(m) val c = foo2(3){ z => println(z) z + 1 } println(c) } }
剛開始完Scala,還有不少不深刻的地方,望高手們多多指點。it