Operators and Methods used in Scala

Operators:

Scala provides a rich set of operators for its basic types.

Types of Operators in Scala:

There are mainly three types of Operators in Scala:

i. Arithmetic Operators: You can invoke arithmetic methods via infix operator notation for addition (+), subtraction (), multiplication (*), division (/), and the remainder (%), on any numeric type.

Example:

scala> 1.2 + 2.3
res6: Double = 3.5
scala> 3 1
res7: Int = 2
scala> 'b' 'a'
res8: Int = 1
scala> 2L * 3L
res9: Long = 6
scala> 11 / 4
res10: Int = 2
scala> 11 % 4
res11: Int = 3
scala> 11.0f / 4.0f
res12: Float = 2.75
scala> 11.0 % 4.0
res13: Double = 3.0

ii. Relational and logical operators:
a. Relational operators: You can compare numeric types with relational methods greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=), which yield a Boolean result. In addition, you can use the unary ‘!’ operator (the unary_! method) to invert a Boolean value.

Example:

 

scala> 1 > 2
res16: Boolean = false
scala> 1 < 2 res17: Boolean = true scala> 1.0 <= 1.0 res18: Boolean = true scala> 3.5f >= 3.6f
res19: Boolean = false
scala> 'a' >= 'A'
res20: Boolean = true
scala> val thisIsBoring = !true
thisIsBoring: Boolean = false
scala> !thisIsBoring
res21: Boolean = true

 

b. Logical operators: The logical methods, logical-and (&&) and logical-or (||), take Boolean operands in infix notation and yield a Boolean result.

Example:

scala> val toBe = true
toBe: Boolean = true
scala> val question = toBe || !toBe
question: Boolean = true
scala> val paradox = toBe && !toBe
paradox: Boolean = false

iii. Bitwise operators: Scala enables you to perform operations on individual bits of integer types with several bitwise methods. The bitwise methods are bitwise-and (&), bitwise-or (|), and bitwise-xor (ˆ).5 The unary bitwise complement operator (~, the method unary_~), inverts each bit in its operand.

Example:

scala> 1 & 2
res24: Int = 0
scala> 1 | 2
res25: Int = 3
scala> 1 ˆ 3
res26: Int = 2
scala> ~1
res27: Int = 2