# Scala高阶函数用法示例和解释详解

## Scala示例：在函数中将函数作为参数传递

``````object MainObject {
def main(args: Array[String]) = {
functionExample(25, multiplyBy2) 	 				// Passing a function as parameter
}
def functionExample(a:Int, f:Int=>AnyVal):Unit = {
println(f(a))   								// Calling that function
}
def multiplyBy2(a:Int):Int = {
a*2
}
}``````

``60``

## Scala示例：函数组成

``````object MainObject {
def main(args: Array[String]) = {
var result = multiplyBy2(add2(10))      // Function composition
println(result)
}
a+2
}

def multiplyBy2(a:Int):Int = {
a*2
}
}``````

``24``

## Scala匿名函数示例

``````object MainObject {
def main(args: Array[String]) = {
var result1 = (a:Int, b:Int) => a+b        // Anonymous function by using => (rocket)
var result2 = (_:Int)+(_:Int)              // Anonymous function by using _ (underscore) wild card
println(result1(10, 10))
println(result2(10, 10))
}
}``````

``````20
20``````

## Scala多行表达式示例

``````def add1(a:Int, b:Int) = {
a
+b
}``````

``````MainObject.scala:3: warning: a pure expression does nothing in statement
position; you may be omitting necessary parentheses
a
^
one warning found

10``````

## Scala示例多行表达式

``````object MainObject {
a+
b
}
(a
+b)
}
def main(args: Array[String]) = {
println(result2+"\n"+result3)
}
}``````

``````20
20``````

## Scala函数库示例

``````object MainObject {
a+b
}
def main(args: Array[String]) = {
println("10 + 10 = "+result)
println("10 + 3 = "+result2)
}
}``````

``20``

## Scala嵌套函数

Scala是一流的函数语言, 这意味着它使你可以传递函数, 返回函数, 组合函数, 嵌套函数等。下面的示例解释了如何定义和调用嵌套函数。

## Scala嵌套函数示例

``````object MainObject {
def add(a:Int, b:Int, c:Int) = {
x+y
}
}
def main(args: Array[String]) = {
var result = add(10, 10, 10)
println(result)
}
}``````

``30``

## Scala示例：具有可变长度参数的函数

``````def add(args: Int*) = {
var sum = 0;
for(a <- args) sum+=a
sum
}
var sum = add(1, 2, 3, 4, 5, 6, 7, 8, 9);
println(sum);``````

``45``

• 回顶