Skip to content

Commit 56cb324

Browse files
committed
Rewrote anonymous function syntax tour
1 parent 919471a commit 56cb324

File tree

1 file changed

+11
-43
lines changed

1 file changed

+11
-43
lines changed

Diff for: tutorials/tour/_posts/2017-02-13-anonymous-function-syntax.md

+11-43
Original file line numberDiff line numberDiff line change
@@ -9,68 +9,36 @@ categories: tour
99
num: 7
1010
next-page: higher-order-functions
1111
previous-page: mixin-class-composition
12+
prerequisite-knowledge: string-interpolation, expression-blocks
1213
---
1314

14-
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.
1616
```tut
1717
(x: Int) => x + 1
1818
```
1919

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.
2721

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:
2923

3024
```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+
}
3230
```
3331

3432
or with no parameter:
3533

3634
```tut
37-
() => { System.getProperty("user.dir") }
35+
() => System.getProperty("user.dir")
3836
```
3937

40-
There is also a very lightweight way to write function types. Here are the types of the three functions defined above:
38+
The types of the three functions defined above are written like so:
4139

4240
```
4341
Int => Int
4442
(Int, Int) => String
4543
() => String
4644
```
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
57-
58-
```tut
59-
object AnonymousFunction {
60-
61-
/**
62-
* Method to increment an integer by one.
63-
*/
64-
val plusOne = (x: Int) => x + 1
65-
66-
/**
67-
* Main method
68-
* @param args application arguments
69-
*/
70-
def main(args: Array[String]) {
71-
72-
println(plusOne(0)) // Prints: 1
73-
74-
}
75-
}
76-
```

0 commit comments

Comments
 (0)