Sunday, July 24, 2016

5 minutes of Scala: Prefix unary operators

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

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"
}
view raw Color.scala hosted with ❤ by GitHub

Note the definition of the method using unary_!. Also remember that only there are 4 supported unary operators: +, -, ! and ~


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