Scala 3 — Book

# 匿名函数

Language

``````val ints = List(1, 2, 3)
``````

``````val doubledInts = ints.map(_ * 2)    // List(2, 4, 6)
``````

``````_ * 2
``````

## 更长的形式

``````val doubledInts = ints.map(_ * 2)
``````

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

``````List<Integer> ints = List.of(1, 2, 3);
List<Integer> doubledInts = ints.stream()
.map(i -> i * 2)
.collect(Collectors.toList());
``````

## 缩短匿名函数

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

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

### 缩短该表达式

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

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

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

``````val doubledInts = ints.map(_ * 2)
``````

### 变得更短

``````ints.foreach((i: Int) => println(i))
``````

``````ints.foreach(i => println(i))
``````

``````ints.foreach(println(_))
``````

``````ints.foreach(println)
``````