Scala function literals && anonymous functions
参考资料:
http://java.dzone.com/articles/scala-function-literals
http://stackoverflow.com/questions/3878347/right-arrow-meanings-in-scala
http://stackoverflow.com/questions/5241147/what-is-a-function-literal-in-scala
http://en.wikibooks.org/wiki/Scala/Function_literals
http://www.jamesward.com/2011/10/17/learning-scala-function-literals
http://dublintech.blogspot.com/2013/01/scala-function-literals.html
function literals 和 anonymous functions 说的是一回事。
Function Literal-直译就是 函数字面量。
A function literal is an alternate(代替的) syntax for defining a function.
We’ve seen function literals already, but to recap(回顾), (i: Int, s: String) => s+i is a
function literal of type Function2[Int,String,String] (String is returned).
You can even use the literal syntax for a type declaration. The following declarations are equivalent:
val f1: (Int, String) => String = (i, s) => s+i val f2: Function2[Int, String, String] = (i, s) => s+i
所以一下几种写法都是相同的,
scala> val f1: (Int,String) => String = (i,s) => s + i f1: (Int, String) => String = <function2> scala> f1(1,"sdsd") res12: String = sdsd1 scala> (i:Int , s:String) => s + i res13: (Int, String) => String = <function2> scala> val f2 = (i:Int , s:String) => s + i f2: (Int, String) => String = <function2> scala> f2(1,"sdsd") res14: String = sdsd1 scala>
val f1: (Int,String) => String = (i,s) => s + i 这个就是说 f1 的类型是 (Int,String) => String
Right Arrow——表示 =>
匿名函数的定义语法,
定义一个匿名函数anonymous function,如下,
scala> (a:Int, b:Int) => a + b res2: (Int, Int) => Int = <function2> scala>
You can bind them to variables:
scala> val add = (a:Int, b:Int) => a + b add: (Int, Int) => Int = <function2> scala> add(1,2) res1: Int = 3 scala>
匿名函数的使用如下,
scala> List(1,2,3,4,5).filter((x: Int)=> x > 3) res4: List[Int] = List(4, 5) scala>
这个匿名函数或者说是函数字面量
(x: Int)=> x > 3
传入list 的 filter函数过滤list集合的元素。
如果匿名函数或者函数字面量的函数体包含多行,可以使用 =>{} 定义
scala> List(1, 2, 3, 4, 5).filter((x: Int) => { | println("x=" + x) | x > 3 | }) x=1 x=2 x=3 x=4 x=5 res6: List[Int] = List(4, 5) scala>
在刚才的第一个示例中,给匿名函数绑定了一个名称,用val 定义的一个常量,如下,
scala> val add = (a:Int, b:Int) => a + b add: (Int, Int) => Int = <function2>
那么这个val add 的常量是什么类型呢,在scala 的 shell 中,返回的 结果是
add: (Int, Int) => Int = <function2>
那么这个就是add 的类型,(Int, Int) => Int
===============END===============