From 658b441c80d90f6f775600054bc540248ce0671b Mon Sep 17 00:00:00 2001 From: Travis Lee Date: Wed, 22 Feb 2017 14:07:38 +0100 Subject: [PATCH] Rewrote operators --- tutorials/tour/_posts/2017-02-13-operators.md | 53 ++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/tutorials/tour/_posts/2017-02-13-operators.md b/tutorials/tour/_posts/2017-02-13-operators.md index 1c29573c49..98fe72ec41 100644 --- a/tutorials/tour/_posts/2017-02-13-operators.md +++ b/tutorials/tour/_posts/2017-02-13-operators.md @@ -9,9 +9,33 @@ categories: tour num: 30 next-page: automatic-closures previous-page: local-type-inference +prerequisite-knowledge: case-classes --- +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: +``` +10.+(1) +``` + +However, it's easier to read as an infix operator: +``` +10 + 1 +``` + +## Defining and using operators +You can use any legal identifier as an operator. This includes a name like `add` or a symbol(s) like `+`. +```tut +case class Vec(val x: Double, val y: Double) { + def +(that: Vec) = new Vec(this.x + that.x, this.y + that.y) +} + +val vector1 = Vec(1.0, 1.0) +val vector2 = Vec(2.0, 2.0) -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`: +val vector3 = vector1 + vector2 +vector3.x // 3.0 +vector3.y // 3.0 +``` +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`: ```tut case class MyBool(x: Boolean) { @@ -30,9 +54,26 @@ def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) This helps to make the definition of `xor` more readable. -Here is the corresponding code in a more traditional object-oriented programming language syntax: - -```tut -def not(x: MyBool) = x.negate -def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate) +## Precedence +When an expression uses multiple operators, the operators are evaluated based on the priority of the first character: +``` +(characters not shown below) +* / % ++ - +: += ! +< > +& +^ +| +(all letters) +``` +This applies to functions you define. For example, the following expression: +``` +a + b ^? c ?^ d less a ==> b | c +``` +Is equivalent to +``` +((a + b) ^? (c ?^ d)) less ((a ==> b) | c) ``` +`?^` has the highest precedence because it starts with the character `?`. `+` has the second highest precedence, followed by `^?`, `==>`, `|`, and `less`.