You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`doubleSalary` is a function which takes a single Int, `x`, and returns `x * 2`. In general, the tuple on the left of the arrow `=>` is a parameter list and the value of the expression on the right is what gets returned. On line 3, the function `doubleSalary` gets applied to each element in the
29
37
list of salaries.
30
38
31
39
To shrink the code, we could make the function anonymous and pass it directly as
32
40
an argument to map:
33
-
```scala:nest
34
-
val salaries = Seq(20000, 70000, 40000)
41
+
42
+
{% tabs map_example_2 class=tabs-scala-version %}
43
+
44
+
{% tab 'Scala 2 and 3' for=map_example_2 %}
45
+
```scala
46
+
valsalaries=Seq(20_000, 70_000, 40_000)
35
47
valnewSalaries= salaries.map(x => x *2) // List(40000, 140000, 80000)
36
48
```
49
+
{% endtab %}
50
+
51
+
{% endtabs %}
52
+
37
53
Notice how `x` is not declared as an Int in the above example. That's because the
38
54
compiler can infer the type based on the type of function map expects (see [Currying](/tour/multiple-parameter-lists.html)). An even more idiomatic way to write the same piece of code would be:
39
55
40
-
```scala mdoc:nest
41
-
valsalaries=Seq(20000, 70000, 40000)
56
+
{% tabs map_example_3 class=tabs-scala-version %}
57
+
58
+
{% tab 'Scala 2 and 3' for=map_example_3 %}
59
+
```scala
60
+
valsalaries=Seq(20_000, 70_000, 40_000)
42
61
valnewSalaries= salaries.map(_ *2)
43
62
```
63
+
{% endtab %}
64
+
65
+
{% endtabs %}
66
+
44
67
Since the Scala compiler already knows the type of the parameters (a single Int),
45
68
you just need to provide the right side of the function. The only
46
69
caveat is that you need to use `_` in place of a parameter name (it was `x` in
@@ -49,6 +72,10 @@ the previous example).
49
72
## Coercing methods into functions
50
73
It is also possible to pass methods as arguments to higher-order functions because
51
74
the Scala compiler will coerce the method into a function.
defforecastInFahrenheit:Seq[Double] = temperatures.map(convertCtoF) // <-- passing the method convertCtoF
96
+
```
97
+
{% endtab %}
98
+
99
+
{% endtabs %}
100
+
60
101
Here the method `convertCtoF` is passed to the higher order function `map`. This is possible because the compiler coerces `convertCtoF` to the function `x => convertCtoF(x)` (note: `x` will
61
102
be a generated name which is guaranteed to be unique within its scope).
62
103
63
104
## Functions that accept functions
64
105
One reason to use higher-order functions is to reduce redundant code. Let's say you wanted some methods that could raise someone's salaries by various factors. Without creating a higher-order function,
0 commit comments