首先是经常使用的匿名函数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