# Scala嵌套方法（NESTEDMETHODS）和多参数列表（Currying）解析

2018-05-16 14:01:42         来源：朝花夕拾

## 嵌套方法（NESTED METHODS）

Scala 中可以定义嵌套方法。以下提供了 factorial 方法用于计算给定数字的阶乘。

``` def factorial(x: Int): Int = {
def fact(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else fact(x - 1, x * accumulator)
}
fact(x, 1)
}
println("Factorial of 2: " + factorial(2))
println("Factorial of 3: " + factorial(3))```

## 多参数列表（Currying）

`def  foldLeft[B](z: B)(op: (B, A) => B): B`

```val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val res = numbers.foldLeft(0)((m, n) => m + n)
print(res) // 55```

## 单个函数参数

`numbers.foldLeft(0, {(m: Int, n: Int) => m + n}) `

`numbers.foldLeft(0)(_ + _)`

```val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val numberFunc = numbers.foldLeft(List[Int]())_
val squares = numberFunc((xs, x) => xs:+ x*x)
print(squares.toString()) // List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
val cubes = numberFunc((xs, x) => xs:+ x*x*x)
print(cubes.toString())  // List(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000)```

## 隐式参数

`def execute(arg: Int)(implicit ec: ExecutionContext) = `