Scala 3 — Book

# 函数变量

Language

``````val doubledInts = ints.map((i: Int) => i * 2)
``````

``````(i: Int) => i * 2
``````

``````val double = (i: Int) => i * 2
``````

``````val double = (i: Int) => i * 2
-----------------
``````

``````val double = (i: Int) => i * 2
------
``````

``````val double = (i: Int) => i * 2
--------
``````

``````scala> val double = (i: Int) => i * 2
val double: Int => Int = ...
``````

### 调用函数

``````val x = double(2)   // 4
``````

``````List(1, 2, 3).map(double)   // List(2, 4, 6)
``````

``````val triple = (i: Int) => i * 3
``````

``````val functionList = List(double, triple)

val functionMap = Map(
"2x" -> double,
"3x" -> triple
)
``````

``````// a List that contains functions of the type `Int => Int`
functionList: List[Int => Int]

// a Map whose keys have the type `String`, and whose
// values have the type `Int => Int`
functionMap: Map[String, Int => Int]
``````

## 关键点

• 要创建函数变量，只需将变量名分配给函数字面量
• 一旦你有了一个函数，你可以像对待任何其他变量一样对待它，即像一个`String``Int`变量