原创转载请注明出处:http://agilestyle.iteye.com/blog/2333597
先看一个简答的例子
package org.fool.scala.functionobjects object DisplayVector extends App { /* Version 1 - DisplayVector */ def show(n: Int): Unit = { println(n) } val v = Vector(1, 2, 3, 4, 5) v.foreach(show) /* Version 2 - DisplayVectorWithAnonymous */ v.foreach(n => println(n)) }
Note:
当作参数传递给其他方法或函数的函数通常都非常小,而且常常只使用一个词。对于强制创建具名方法然后将其当做参数传递这种做法,会带来额外的工作量,也会给程序阅读者带来额外的困扰。因此我们可以改为定义一个函数,但不给出名字,称为匿名函数
匿名函数是使用“=>”符号定义的,符号的左边是参数列表,而右边是单个表达式(可以是组合表达式),改表达式将产生函数的结果
Console Output
如果需要多个参数,那么就必须对参数列表使用括号,仍然可以利用类型推断:
package org.fool.scala.functionobjects object TwoArgAnonymous extends App { val v = Vector(29, 37, 15, 3, 11) println(v.sorted) val sortedByDesc = v.sortWith((i, j) => j < i) println(sortedByDesc) }
Console Output
具有0个参数的函数也可以是匿名的。“=>”和Unit合起来表示不返回任何信息
package org.fool.scala.functionobjects class Later(val f: () => Unit) { def call(): Unit = { f() } } object CallLater extends App { val l = new Later(() => println("no args")) l.call() // assign an anonymous function to a var or val val later1 = () => println("now") val later2 = () => println("now") later1() later2() }
Console Output