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
Any method which takes a single parameter can be used as an *infix operator* in Scala. Here is the definition of class `MyBool` which defines three methods `and`, `or`, and `negate`.
13
+
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`:
14
14
15
15
```tut
16
-
class MyBool(x: Boolean) {
16
+
case class MyBool(x: Boolean) {
17
17
def and(that: MyBool): MyBool = if (x) that else this
18
18
def or(that: MyBool): MyBool = if (x) this else that
19
-
def negate: MyBool = new MyBool(!x)
19
+
def negate: MyBool = MyBool(!x)
20
20
}
21
21
```
22
22
23
23
It is now possible to use `and` and `or` as infix operators:
24
24
25
25
```tut
26
-
def not(x: MyBool) = xnegate; // semicolon required here
26
+
def not(x: MyBool) = x.negate
27
27
def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
28
28
```
29
29
30
-
As the first line of this code shows, it is also possible to use nullary methods as postfix operators. The second line defines an `xor` function using the `and` and `or` methods as well as the new `not` function. In this example the use of _infix operators_ helps to make the definition of `xor` more readable.
30
+
This helps to make the definition of `xor` more readable.
31
31
32
32
Here is the corresponding code in a more traditional object-oriented programming language syntax:
33
33
34
34
```tut
35
-
def not(x: MyBool) = x.negate; // semicolon required here
0 commit comments