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:
41
+
42
+
{% tabs map_example_2 %}
43
+
44
+
{% tab 'Scala 2 and 3' for=map_example_2 %}
33
45
```scala:nest
34
-
val salaries = Seq(20000, 70000, 40000)
46
+
val salaries = Seq(20_000, 70_000, 40_000)
35
47
val newSalaries = salaries.map(x => x * 2) // List(40000, 140000, 80000)
36
48
```
49
+
{% end tab %}
50
+
51
+
{% end tabs %}
37
52
Notice how `x` is not declared as an Int in the above example. That's because the
38
53
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
54
55
+
{% tabs map_example_3 %}
56
+
57
+
{% tab 'Scala 2 and 3' for=map_example_3 %}
40
58
```scala mdoc:nest
41
-
valsalaries=Seq(20000, 70000, 40000)
59
+
valsalaries=Seq(20_000, 70_000, 40_000)
42
60
valnewSalaries= salaries.map(_ *2)
43
61
```
62
+
{% end tab %}
63
+
64
+
{% end tabs %}
65
+
44
66
Since the Scala compiler already knows the type of the parameters (a single Int),
45
67
you just need to provide the right side of the function. The only
46
68
caveat is that you need to use `_` in place of a parameter name (it was `x` in
@@ -49,6 +71,10 @@ the previous example).
49
71
## Coercing methods into functions
50
72
It is also possible to pass methods as arguments to higher-order functions because
51
73
the Scala compiler will coerce the method into a function.
defforecastInFahrenheit:Seq[Double] = temperatures.map(convertCtoF) // <-- passing the method convertCtoF
95
+
```
96
+
{% end tab %}
97
+
98
+
{% end tabs %}
99
+
60
100
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
101
be a generated name which is guaranteed to be unique within its scope).
62
102
63
103
## Functions that accept functions
64
104
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