Scala提供了相对轻量级的语法来定义匿名函数。下面表达式创建了一个整数加1函数。
(x: Int) => x + 1这是下面匿名类定义的简写:
new Function1[Int, Int] { def apply(x: Int): Int = x + 1 }也可以定义带多个参数的函数:
(x: Int, y: Int) => "(" + x + ", " + y + ")"或者不带参数:
() => { System.getProperty("user.dir") }还有一种非常轻量级的方式来写函数类型。下面是上面定义的三个函数的类型:
Int => Int (Int, Int) => String () => String这个语法是下面类型的简写:
Function1[Int, Int] Function2[Int, Int, String] Function0[String]下面展示了如何使用开始那个匿名函数。
object AnonymousFunction { /** * Method to increment an integer by one. */ val plusOne = (x: Int) => x + 1 /** * Main method * @param args application arguments */ def main(args: Array[String]) { println(plusOne(0)) // Prints: 1 } }