Well, I am reading the book Programming in Scala, and I am discovering new capabilities of this language. Today I want to talk about unary operators (also called prefix operators).
The only identifiers that can be used as prefix operators are +, -, ! and ~
Then you have to define your method using unary_<here your operator>, and you could invoke that method using prefix operator notation, such as <your operator><your variable>.
I know maybe all of this, is a bit confusing but seeing code all will be more easy.
Imagine, we want to implement our class Color. This class defines a color using three pixels (red, green, blue). Also we want operate with our Color class, and one required operation is the capability to inverting the color. As Java programmer, I would define a method called inverse, and I would call it in this way : myColor.inverse() . It is a good approach, totally acceptable, but here is when the magic of unary operators comes, you can do the same in Scala with this : !myColor
Note the definition of the method using unary_!. Also remember that only there are 4 supported unary operators: +, -, ! and ~
No comments:
Post a Comment