Skip to content

Commit 658b441

Browse files
committed
Rewrote operators
1 parent ea9b5ad commit 658b441

File tree

1 file changed

+47
-6
lines changed

1 file changed

+47
-6
lines changed

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

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,33 @@ categories: tour
99
num: 30
1010
next-page: automatic-closures
1111
previous-page: local-type-inference
12+
prerequisite-knowledge: case-classes
1213
---
14+
In Scala, operators are methods. Any method with a single parameter can be used as an _infix operator_. For example, `+` can be called with dot-notation:
15+
```
16+
10.+(1)
17+
```
18+
19+
However, it's easier to read as an infix operator:
20+
```
21+
10 + 1
22+
```
23+
24+
## Defining and using operators
25+
You can use any legal identifier as an operator. This includes a name like `add` or a symbol(s) like `+`.
26+
```tut
27+
case class Vec(val x: Double, val y: Double) {
28+
def +(that: Vec) = new Vec(this.x + that.x, this.y + that.y)
29+
}
30+
31+
val vector1 = Vec(1.0, 1.0)
32+
val vector2 = Vec(2.0, 2.0)
1333
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`:
34+
val vector3 = vector1 + vector2
35+
vector3.x // 3.0
36+
vector3.y // 3.0
37+
```
38+
The class Vec has a method `+` which we used to add `vector1` and `vector2`. Using parentheses, you can build up complex expressions with readable syntax. Here is the definition of class `MyBool` which includes methods `and` and `or`:
1539

1640
```tut
1741
case class MyBool(x: Boolean) {
@@ -30,9 +54,26 @@ def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
3054

3155
This helps to make the definition of `xor` more readable.
3256

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)
57+
## Precedence
58+
When an expression uses multiple operators, the operators are evaluated based on the priority of the first character:
59+
```
60+
(characters not shown below)
61+
* / %
62+
+ -
63+
:
64+
= !
65+
< >
66+
&
67+
^
68+
|
69+
(all letters)
70+
```
71+
This applies to functions you define. For example, the following expression:
72+
```
73+
a + b ^? c ?^ d less a ==> b | c
74+
```
75+
Is equivalent to
76+
```
77+
((a + b) ^? (c ?^ d)) less ((a ==> b) | c)
3878
```
79+
`?^` has the highest precedence because it starts with the character `?`. `+` has the second highest precedence, followed by `^?`, `==>`, `|`, and `less`.

0 commit comments

Comments
 (0)