# Scala高阶函数（HIGHER-ORDERFUNCTIONS)解析

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

```val salaries = Seq(20000, 70000, 40000)
val doubleSalary = (x: Int) => x * 2
val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000)```

doubleSalary 函数有一个 Int 类型的参数 x ,并返回 x * 2 。通常，箭头 => 左侧的元组(tuple)是一个参数列表，右侧表达式的计算结果就是返回值。在第三行代码中，doubleSalary 函数被应用到 salaries 列表的每一个元素上。

```val salaries = Seq(20000, 70000, 40000)
val newSalaries = salaries.map(x => x * 2) // List(40000, 140000, 80000)```

```val salaries = Seq(20000, 70000, 40000)
val newSalaries = salaries.map(_ * 2)```

## 方法强制转换为函数

```case class WeeklyWeatherForecast(temperatures: Seq[Double]) {
private def convertCtoF(temp: Double) = temp * 1.8 + 32
def forecastInFahrenheit: Seq[Double] = temperatures.map(convertCtoF) // <-- passing the method convertCtoF
}```

## 接收函数的函数

```object SalaryRaiser {

def smallPromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * 1.1)

def greatPromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * math.log(salary))

def hugePromotion(salaries: List[Double]): List[Double] =
salaries.map(salary => salary * salary)
}```

```object SalaryRaiser {

private def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] =
salaries.map(promotionFunction)

def smallPromotion(salaries: List[Double]): List[Double] =
promotion(salaries, salary => salary * 1.1)

def bigPromotion(salaries: List[Double]): List[Double] =
promotion(salaries, salary => salary * math.log(salary))

def hugePromotion(salaries: List[Double]): List[Double] =
promotion(salaries, salary => salary * salary)
}```

## 返回函数的函数

```def urlBuilder(ssl: Boolean, domainName: String): (String, String) => String = {
val schema = if (ssl) "https://" else "https://"
(endpoint: String, query: String) => s"\$schema\$domainName/\$endpoint?\$query"
}
val domainName = "www.example.com"
def getURL = urlBuilder(ssl=true, domainName)
val endpoint = "users"
val query = "id=1"
val url = getURL(endpoint, query) // "https://www.example.com/users?id=1": String```