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
Copy file name to clipboardExpand all lines: tutorials/tour/_posts/2017-02-13-operators.md
+47-6Lines changed: 47 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -9,9 +9,33 @@ categories: tour
9
9
num: 30
10
10
next-page: automatic-closures
11
11
previous-page: local-type-inference
12
+
prerequisite-knowledge: case-classes
12
13
---
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 `+`.
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`:
15
39
16
40
```tut
17
41
case class MyBool(x: Boolean) {
@@ -30,9 +54,26 @@ def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
30
54
31
55
This helps to make the definition of `xor` more readable.
32
56
33
-
Here is the corresponding code in a more traditional object-oriented programming language syntax:
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)
38
78
```
79
+
`?^` has the highest precedence because it starts with the character `?`. `+` has the second highest precedence, followed by `^?`, `==>`, `|`, and `less`.
0 commit comments