8000 Rewrote operators · scala/docs.scala-lang@27b4189 · GitHub
[go: up one dir, main page]

Skip to content

Commit 27b4189

Browse files
committed
Rewrote operators
1 parent bcef8df commit 27b4189

File tree

1 file changed

+34
-9
lines changed

1 file changed

+34
-9
lines changed

tutorials/tour/_posts/2017-02-13-operators.md

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,40 @@ num: 30
1010
next-page: automatic-closures
1111
previous-page: local-type-inference
1212
---
13+
In Scala, operators are methods. For example, `+` can be called with dot-notation:
14+
```
15+
10.+(1)
16+
```
17+
18+
However, it more closely resembles math if you write it as an infix operator:
19+
```
20+
10 + 1
21+
```
22+
23+
You can also give `+` specific meaning in your class:
24+
```tut
25+
class Vector(val x: Double, val y: Double) {
26+
def +(that: Vector) = new Vector(this.x + that.x, this.y + that.y)
27+
}
28+
29+
val vector1 = new Vector(1.0, 1.0)
30+
val vector2 = new Vector(2.0, 2.0)
31+
32+
val vector3 = vector1 + vector2
33+
vector3.x // 3.0
34+
vector3.y // 3.0
35+
```
36+
The class vector has a method `+` which we used to add vector1 and vector2. When the method has two or more parameters, use a tuple:
37+
```
38+
class Rectangle(val x: Double, val y: Double) {
39+
def changeSize(dx: Int, dy: Int): Rectangle = new Rectangle(x + dx, y + dy)
40+
}
41+
42+
val rect1 = new Rectangle(1, 2)
43+
val rect2 = rect1 changeSize (2, 2) // equivalent to rect1.changeSize(2, 2)
44+
```
1345

14-
Any method which takes a single parameter can be used as an *infix operator* in Scala. Here is the definition of class `MyBool` which includes methods `and` and `or`:
46+
Using parentheses, you can build up complex expressions with readable syntax. Here is the definition of class `MyBool` which includes methods `and` and `or`:
1547

1648
```tut
1749
case class MyBool(x: Boolean) {
@@ -28,11 +60,4 @@ def not(x: MyBool) = x.negate
2860
def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
2961
```
3062

31-
This helps to make the definition of `xor` more readable.
32-
33-
Here is the corresponding code in a more traditional object-oriented programming language syntax:
34-
35-
```tut
36-
def not(x: MyBool) = x.negate
37-
def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate)
38-
```
63+
This helps to make the definition of `xor` more readable.If the method takes more than one argument, use a tuple:

0 commit comments

Comments
 (0)
0