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
Scala provides a relatively lightweight syntax for defining anonymous functions. The following expression creates a successor function for integers:
15
-
15
+
Anonymous functions are functions which are not assigned to an identifier. On the left of the arrow `=>` is a parameter list, and on the right is an expression.
16
16
```tut
17
17
(x: Int) => x + 1
18
18
```
19
19
20
-
This is a shorthand for the following anonymous class definition:
21
-
22
-
```tut
23
-
new Function1[Int, Int] {
24
-
def apply(x: Int): Int = x + 1
25
-
}
26
-
```
20
+
Anonymous functions are not very useful by themselves but they have a value which can be used as an argument of another function or the return value of another function. This will be covered later in the tour.
27
21
28
-
It is also possible to define functions with multiple parameters:
22
+
It is also possible to define functions with multiple parameters and/or an expression block:
29
23
30
24
```tut
31
-
(x: Int, y: Int) => "(" + x + ", " + y + ")"
25
+
(x: Int, y: Int) => {
26
+
val xSquared = x * x
27
+
val ySquared = y * y
28
+
s"($xSquared, $ySquared)"
29
+
}
32
30
```
33
31
34
32
or with no parameter:
35
33
36
34
```tut
37
-
() => { System.getProperty("user.dir") }
35
+
() => System.getProperty("user.dir")
38
36
```
39
37
40
-
There is also a very lightweight way to write function types. Here are the types of the three functions defined above:
38
+
The typesof the three functions defined above are written like so:
41
39
42
40
```
43
41
Int => Int
44
42
(Int, Int) => String
45
43
() => String
46
44
```
47
-
48
-
This syntax is a shorthand for the following types:
49
-
50
-
```
51
-
Function1[Int, Int]
52
-
Function2[Int, Int, String]
53
-
Function0[String]
54
-
```
55
-
56
-
The following example shows how to use anonymous function of the beginning of this page
0 commit comments