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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Color { | |
def create(r: Int, g: Int, b: Int): Color = { | |
new Color(r, g, b) | |
} | |
} | |
class Color(r: Int, g: Int, b: Int) { | |
def unary_! = { | |
new Color(255-r, 255-g, 255-b) | |
} | |
def getR() : Int = r | |
def getG() : Int = g | |
def getB() : Int = b | |
override def toString(): String = s"r: $r, g: $g, b: $b" | |
} |
Note the definition of the method using unary_!. Also remember that only there are 4 supported unary operators: +, -, ! and ~
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object MyCoolApp { | |
def main(args: Array[String]): Unit = { | |
val myColor = Color.create(23, 14, 9) | |
println("Initial color: " + myColor) | |
val inverseColor1 = !myColor | |
println("Inverse color: " + inverseColor1) | |
println("Inverse color again: " + !inverseColor1) | |
} | |
} |
No comments:
Post a Comment