首先是常用的匿名函数
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 //忽略所有参数,直接返回定值
接着是模式匹配匿名函数
BNF描述如下
BlockExpr ::= ‘{’ CaseClauses ‘}’
CaseClauses ::= CaseClause {CaseClause}
CaseClause ::= ‘case’ Pattern [Guard] ‘=>’ Block
常见使用方式如下
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
}
下面的代码是我自己些的一段测试
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,还有很多不深入的地方,望高手们多多指点。