原創轉載請註明出處: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