This article records my understanding of scala language operator overloading.
Operator = Method
For Scala, operators are common methods (coupled with someSyntactic sugar). For example, the following class is reloaded.Plus signAndMinus sign:
We can use Myint as follows:
var myInt = new MyInt(1)myInt = myInt + 1
You can use javap or classpy to analyze the classes compiled by scalac. + actually corresponds
$ Plus ()Method,-corresponding
$ Minus ()Method. That is to say, the following three lines of code are equivalent:
myInt = myInt + 1myInt = myInt.+(1)myInt = myInt.$plus(1)
Multi-symbol Operators
A multi-symbol operator is nothing more than a simple combination of a single operator. It adds a multi-symbol operator to Myint.++, As shown below:
You can use ++ as follows:
var myInt = new MyInt(1)myInt = myInt +++ 1
Decompile Myint. Class. scalac compiles the ++ operator
$ Plus ()Method.
OP = syntactic sugar
If a class is overloaded with the op operatorOP =Then the scala compiler willX op = yReplaceX = x op y, That isX = x. OP (y)The Code is as follows:
var myInt = new MyInt(1)myInt += 1 // myInt = myInt + 1
Binding rules
If the operatorColonEnd, the operator willBind(BIND) to the right operand, that is,X op: YEquivalentY. Op :( X). We add+:OPERATOR:
You can use the +: operator as follows:
var myInt = new MyInt(1)println(1 +: myInt) // myInt.+:(1)
Parentheses syntactic sugar
If a class is definedApply ()Method, scala provides syntax sugar to make the instance of this class look likeFunction(Can be called directly) orArray(Elements can be accessed by subscript ). If the class is definedUpdate ()Method, you can assign values by subscript like an array. For example, the following pair class:
You can use the pair class as follows:
val xy = new Pair(Array(3, 7))println(xy(0)) // 3println(xy(1)) // 7xy(0) = 11xy(1) = 18println(xy(0)) // 11println(xy(1)) // 18
Operator comparison table
The following table compares the operators I have compiled with Scala internal names:
+ |
$ Plus |
- |
$ Minus |
* |
$ Times |
/ |
$ Div |
% |
$ Percent |
& |
$ Amp |
| |
$ Bar |
^ |
$ Up |
~ |
$ Tilde |
> |
$ Greater |
< |
$ Less |
! |
$ Bang |
? |
$ Qmark |
= |
$ EQ |
: |
$ Colon |
@ |
$ |
# |
$ Hash |
\ |
$ Bslash |
$ |
$ |
References
Http://www.scala-lang.org/documentation/
Http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators
Scala Study Notes (1) -- Operator Overloading