Open In App

Operators in Scala

Last Updated : 31 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: 

Arithmetic Operators

These are used to perform arithmetic/mathematical operations on operands.  

  • Addition(+) operator adds two operands. For example, x+y.
  • Subtraction(-) operator subtracts two operands. For example, x-y.
  • Multiplication(*) operator multiplies two operands. For example, x*y.
  • Division(/) operator divides the first operand by the second. For example, x/y.
  • Modulus(%) operator returns the remainder when the first operand is divided by the second. For example, x%y.
  • Exponent(**) operator returns exponential(power) of the operands. For example, x**y.

Example:  

Scala




// Scala program to demonstrate
// the Arithmetic Operators
 
object Arithop
{
 
def main(args: Array[String])
{
    // variables
    var a = 50;
    var b = 30;
     
    // Addition
    println("Addition of a + b = " + (a + b));
     
    // Subtraction
    println("Subtraction of a - b = " + (a - b));
     
    // Multiplication
    println("Multiplication of a * b = " + (a * b));
     
    // Division
    println("Division of a / b = " + (a / b));
     
    // Modulus
    println("Modulus of a % b = " + (a % b));
 
}
}


Output: 

Addition of a + b = 80
Subtraction of a - b = 20
Multiplication of a * b = 1500
Division of a / b = 1
Modulus of a % b = 20

Relational Operators

Relational operators or Comparison operators are used for comparison of two values. Let’s see them one by one: 

  • Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.
  • Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
  • Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
  • Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
  • Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
  • Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.

Example:

Scala




// Scala program to demonstrate
// the Relational Operators
object Relop
{
 
def main(args: Array[String])
{
    // variables
    var a = 50;
    var b = 30;
     
    // Equal to operator
    println("Equality of a == b is : " + (a == b));
     
    // Not equal to operator
    println("Not Equals of a != b is : " + (a != b));
     
    // Greater than operator
    println("Greater than of a > b is : " + (a > b));
     
    // Lesser than operator
    println("Lesser than of a < b is : " + (a < b));
 
    // Greater than equal to operator
    println("Greater than or Equal to of a >= b is : " + (a >= b));
     
    // Lesser than equal to operator
    println("Lesser than or Equal to of a <= b is : " + (a <= b));
 
}
}


Output: 

Equality of   a == b is : false
Not Equals of a != b is : true
Greater than of a > b is : true
Lesser than of  a = b is : true
Lesser than or Equal to of a <= b is : false

Logical Operators

They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

  • Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero).
  • Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
  • Logical NOT(!) operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false.

Example:

Scala




// Scala program to demonstrate
// the Logical Operators
object Logop
{
 
def main(args: Array[String])
{
     
    // variables
    var a = false
    var b = true
     
    // logical NOT operator
    println("Logical Not of !(a && b) = " + !(a && b));
     
    // logical OR operator
    println("Logical Or of a || b = " + (a || b));
     
    // logical AND operator
    println("Logical And of a && b = " + (a && b));
 
}
}


Output: 

Logical Not of !(a && b) = true
Logical Or of a || b = true
Logical And of a && b = false

Assignment Operators

Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. 
Different types of assignment operators are shown below: 

  • Simple Assignment (=) operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
  • Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left.
  • Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left.
  • Multiply AND Assignment (*=) operator is used for multiplying the left operand with right operand and then assigning it to the variable on the left.
  • Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left.
  • Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to the variable on the left.
  • Exponent AND Assignment (**=) operator is used for raising power of the left operand to the right operand and assigning it to the variable on the left.
  • Left shift AND Assignment(<<=)operator is used to perform binary left shift of the left operand with the right operand and assigning it to the variable on the left.
  • Right shift AND Assignment(>>=)operator is used to perform binary right shift of the left operand with the right operand and assigning it to the variable on the left.
  • Bitwise AND Assignment(&=)operator is used to perform Bitwise And of the left operand with the right operand and assigning it to the variable on the left.
  • Bitwise exclusive OR and Assignment(^=)operator is used to perform Bitwise exclusive OR of the left operand with the right operand and assigning it to the variable on the left.
  • Bitwise inclusive OR and Assignment(|=)operator is used to perform Bitwise inclusive OR of the left operand with the right operand and assigning it to the variable on the left.

Example: 

Scala




// Scala program to demonstrate
// the Assignments Operators
object Assignop
{
 
def main(args: Array[String])
{
     
    // variables
    var a = 50;
    var b = 40;
    var c = 0;
     
    // simple addition
    c = a + b;
    println("simple addition: c= a + b = " + c);
     
    // Add AND assignment
    c += a;
    println("Add and assignment of c += a = " + c);
     
    // Subtract AND assignment
    c -= a;
    println("Subtract and assignment of c -= a = " + c);
     
    // Multiply AND assignment
    c *= a;
    println("Multiplication and assignment of c *= a = " + c);
     
    // Divide AND assignment
    c /= a;
    println("Division and assignment of c /= a = " + c);
     
    // Modulus AND assignment
    c %= a;
    println("Modulus and assignment of c %= a = " + c);
     
    // Left shift AND assignment
    c <<= 3;
    println("Left shift and assignment of c <<= 3 = " + c);
     
    // Right shift AND assignment
    c >>= 3;
    println("Right shift and assignment of c >>= 3 = " + c);
     
    // Bitwise AND assignment
    c &= a;
    println("Bitwise And assignment of c &= 3 = " + c);
     
    // Bitwise exclusive OR and assignment
    c ^= a;
    println("Bitwise Xor and assignment of c ^= a = " + c);
     
    // Bitwise inclusive OR and assignment
    c |= a;
    println("Bitwise Or and assignment of c |= a = " + c);
}
}


Output: 

simple addition: c= a + b = 90
Add and assignment of c += a = 140
Subtract and assignment of c -= a = 90
Multiplication and assignment of c *= a = 4500
Division and assignment of c /= a = 90
Modulus and assignment of c %= a = 40
Left shift and assignment of c <<= 3 = 320
Right shift and assignment of c >>= 3 = 40
Bitwise And assignment of c &= 3 = 32
Bitwise Xor and assignment of c ^= a = 18
Bitwise Or and assignment of c |= a = 50

Bitwise Operators

In Scala, there are 7 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators : 

  • Bitwise AND (&): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
  • Bitwise OR (|): Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
  • Bitwise XOR (^): Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • Bitwise left Shift (<<): Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
  • Bitwise right Shift (>>): Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
  • Bitwise ones Complement (~): This operator takes a single number and used to perform the complement operation of 8-bit.
  • Bitwise shift right zero fill(>>>): In shift right zero fill operator, left operand is shifted right by the number of bits specified by the right operand, and the shifted values are filled up with zeros.

Example: 

Scala




// Scala program to demonstrate
// the Bitwise Operators
object Bitop
{
def main(args: Array[String])
{
    // variables
    var a = 20;
    var b = 18;
    var c = 0;
     
    // Bitwise AND operator
    c = a & b;
    println("Bitwise And of a & b = " + c);
     
    // Bitwise OR operator
    c = a | b;
    println("Bitwise Or of a | b = " + c);
     
    // Bitwise XOR operator
    c = a ^ b;
    println("Bitwise Xor of a ^ b = " + c);
     
    // Bitwise once complement operator
    c = ~a;
    println("Bitwise Ones Complement of ~a = " + c);
     
    // Bitwise left shift operator
    c = a << 3;
    println("Bitwise Left Shift of a << 3 = " + c);
     
    // Bitwise right shift operator
    c = a >> 3;
    println("Bitwise Right Shift of a >> 3 = " + c);
     
    // Bitwise shift right zero fill operator
    c = a >>> 4;
    println("Bitwise Shift Right a >>> 4 = " + c);
}
}


Output: 

Bitwise And of a & b = 16
Bitwise Or of a | b = 22
Bitwise Xor of a ^ b = 6
Bitwise Ones Complement of ~a = -21
Bitwise Left Shift of a << 3 = 160
Bitwise Right Shift of a >> 3 = 2
Bitwise Shift Right a >>> 4 = 1


Previous Article
Next Article

Similar Reads

Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Scala short &lt;(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short &lt;(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
How to Install Scala IDE For Eclipse?
In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have JDK installed, you may get them from this link. I
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -&gt; &quot;geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &amp;() method with example
The &amp;() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &amp;() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int &lt;(x: Char) method with example
The &lt;(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).&lt;(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int &lt;=(x: Double) method with example
The &lt;=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int &lt;=(x: Byte) method with example
The &lt;=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Parameterless Method in Scala
Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle. Exa
2 min read
Scala short /(x: Short): Int
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The /(x: Short) method is utilized to return a result of the quotient operation on the specified Short value by the x. Method Definition: def /(x: Short): Int Return Type: It returns quotient with value and x. Example #1: // Scala program of Sho
1 min read
Scala List isEmpty Operation with example
The isEmpty operation is utilized to check if the stated list is empty or not. Syntax: m1.isEmpty Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false. Example #1: // Scala program of isEmpty() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set dropRight() method with example
The dropRight() is utilized to return all elements except last 'n' elements. Method Definition: def dropRight(n: Int): Set[A] Return Type: It returns a set containing all elements except last 'n' elements. Example #1: // Scala program of dropRight() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set equals() method with example
The equals() method is utilized to check whether the two sets have the same elements or not. Method Definition: def equals(that: Any): Boolean Return Type: It returns true if the elements of both the sets are same else it returns false. Example #1: // Scala program of equals() // method // Creating object object GfG { // Main method def main(args:A
1 min read
Scala Set drop() method with example
The drop() method is utilized to delete the first ‘n’ elements or to return all elements except first 'n' elements. Method Definition: def drop(n: Int): Set[A]] Return Type: It returns all elements except first 'n' elements. Example #1: // Scala program of drop() // method // Creating object object GfG { // Main method def main(args:Array[String])
1 min read
Article Tags :