Operators in Kotlin – Arithmetic, Invoke And More

An operator is a symbol that tell the compiler to perform specific operation on the operand/s. Some operators can be applied on single operand while some are applied on the set of operands. We have following types of operators in kotlin –

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. In Operators
7. Invoke Operator
8. Indexed access Operator
9. Unary Prefix Operators

1. Kotlin Arithmetic operators

In Kotlin, we have following types of Arithmetic operators in kotlin.

Operators Expression Equivalent To Description
+ a + b a.plus(b) Used for Addition
a – b a.minus(b) Used for Subtraction
* a * b a.times(b) Used for multiplication
/ a / b a.div(b) Used for division
% a % b a.mod(b) Used to get remainder when a number is divided by another number
– Example
fun main(args: Array<String>) {

    val a = 20
    val b = 3
    var result: Int

    println("a = $a , b = $b")

    result = a + b
    println("a + b = $result")

    result = a - b
    println("a - b = $result")

    result = a * b
    println("a * b = $result")

    result = a / b
    println("a / b = $result")

    result = a % b
    println("a % b = $result")
}

When you run the program, the output will be –

a = 20 , b = 3
a + b = 23
a – b = 17
a * b = 60
a / b = 6
a % b = 2

You can also use + operator for concatenating two strings values.

var firstName = “Rahul ”
var lastName = “Kumar ”
var fullName = firstName + lastName;

Complete Example of concatenating two strings.

fun main(args:  Array<String>) {

	var firstName = "Rahul "
	var lastName = "Kumar "
	var fullName = firstName + lastName;

	println("FullName is $fullName")
} 

Output:

FullName is Rahul Kumar

(++) Increment Operator In Kotlin

Like Other languages, ++ is called increment operator in Kotlin. We can use this operator either as prefix or as postfix. Let’s say, A is a variable. We denote prefix representation as ++A and postfix representation as A++.

– Example
fun main(args:  Array<String>) {

    var A = 10
    var B = ++A
    println("Prefix:  A = $A,  B = $B")

    var a = 10
    var b = a++
    println("Postfix:  a=  $a, b = $b")
} 

– Explanation:

The statement B = ++A means:
      a. Increment the value of A by 1 i.e. A = A+1
      b. Assign the incremented value to variable B.

The statement b = a++ means:
      a. Assign the value of a to b.
      b. Increment the value of a by 1 i.e. a = a+1

(- -) Decrement Operator in Kotlin

Like Other languages, – – is called decrement operator in Kotlin. We can use this operator either as prefix or as postfix. Let’s say A is a variable. We denote prefix representation as – – A and postfix representation as A- -.

– Example
fun main(args:  Array<String>) {

    var A = 10
    var B = --A
    println("Prefix:  A = $A,  B = $B")

    var a = 10
    var b = a--
    println("Postfix:  a=  $a, b = $b")
} 

– Explanation:
The statement B = – – A means:
    a. Decrement the value of A by 1 i.e. A = A – 1
    b. Assign the decremented value to variable B.

The statement b = a – – means:
    a. Assign the value of a to b.
    b. Decrement the value of a by 1 i.e. a = a – 1




How does Operators in Kotlin actually work?

Any operator in kotlin has set of functions that are designed to work with built-in data types. When we use any operator, compiler checks the datatype of operand and calls a particular function. Then, result of the called function is returned.

– Example

Although, we are taking example of + operator, it is valid for other operators in kotlin as well.

Let’s say we have 3 variables A, B and C. We are assigning the sum of B and C to A.

A = B + C

When compiler processes, it performs following steps.

a. Determines the type of B and C. Let it be T and T’ respectively.
b. Looks up a function plus() that takes parameter of data type T’.
c. Then, it performs the required operation and return the result.

Did you know?

You can check the functions defined for + operator using trick to check. You will find that we have below functions for plus operation in kotlin. These methods are defined in Primitives.kt file.

/** Adds the other value to this value. */
public operator fun plus(other: Byte): Int
/** Adds the other value to this value. */
public operator fun plus(other: Short): Int
/** Adds the other value to this value. */
public operator fun plus(other: Int): Int
/** Adds the other value to this value. */
public operator fun plus(other: Long): Long
/** Adds the other value to this value. */
public operator fun plus(other: Float): Float
/** Adds the other value to this value. */
public operator fun plus(other: Double): Double

2. Kotlin Assignment Operators

Assignment operators are used to assign value to a variable. It can be used anywhere in the program. For example,

var a = 87;

Here, = is an assignment operator that have been used to assign an integer value 87 to variable a.

We have following assignment operators in Kotlin,

Operators Expression Equivalent to Description
+= a += b a = a + b Add a to b and assign to a
-= a -= b a = a – b Subtract b from a and assign to a
*= a *= b a = a * b Multiply a and b and assign to a
/= a /= b a = a / b Divide a by b and assign to a
%= a %= b a = a % b Divide a by b and assign the remainder to a
– Example
fun main(args: Array<String>) {
    var a = 60

    var b = 50
    b += 5

    var c = 50
    c -= 5

    var d = 50
    d *= 5

    var e = 50
    e /= 5

    var f = 53
    f %= 5

    println("a  = $a")
    println("b  = $b")
    println("c  = $c")
    println("d  = $d")
    println("e  = $e")
    println("f  = $f")
}

When you run the program, you will get below output:

a = 60
b = 55
c = 45
d = 250
e = 10
f = 3

3. Kotlin Relational Operators

Relational operators are binary operators that are used to determine whether one of the operand is smaller, greater or equal than other operand.
We have following relational operators in kotlin.

Operators Expression Equivalent to Description
== a == b a?.equals(b) ?: (b === null) Checks whether a is equal to b or not
!= a != b !(a?.equals(b) ?: (b === null)) Checks whether a is not equal to b or not
> a > b a.compareTo(b) > 0 Checks whether a is greater than b
< a < b a.compareTo(b) < 0 Checks whether a is smaller than b or not
>= a >= b a.compareTo(b) >= 0 Checks whether a is greater than or equal to b or not
<= a <= b a.compareTo(b) <= 0 Checks whether a is smaller than or equal to b or not
– Example
fun main(args:  Array<String>) {

	var a = 20
	var b = 30

	var c: Boolean

	c = a == b
	println("a == b : $c")

	c = a != b
	println("a != b : $c")

	c = a > b
	println("a > b : $c")

	c = a < b
	println("a < b : $c")

	c = a >= b
	println("a >= b : $c")

	c = a <= b
	println("a <= b : $c")
} 

When you run the program, you will get below output:
a == b : false
a != b : true
a > b : false
a < b : true a >= b : false
a <= b : true




4. Kotlin Logical Operators

Below are list of supported Logical operators in kotlin.

Operators Expression Equivalent to Description
! !a a.not() Logical NOT a. If a is true, !a is false and vice-versa
&& a && b a.and(b) Returns true iff a and b both are true
|| a || b a.or(b) Returns true if either a or b or both are true
– Example
fun main(args:  Array<String>) {

	var a = false
	var b = !a
	println("a = $a, b = $b")

	var c = false
	var d = c && a
	var e = c || b
	println("d = $d, e = $e")
} 

When you run the program, you will get below output:
a = false, b = true
d = false, e = true

5. Kotlin Bitwise Operator

Unlike Java, there is no bitwise operators in kotlin to perform actions in bits of operands. However, You can achieve it by the various pre-defined functions in kotlin.
They operates on bits of operand/s. It performs bit-by-bit action. When we use such function, At first, operands are converted into bit. Then, actions are taken according to functions used.

Below are list of pre-defined functions in kotlin.

Functions Description
and Performs bitwise AND operations
or Performs bitwise OR operations
xor performs bitwise XOR operation
inv Performs Bitwise inversion
shl Performs signed shift left
shr Performs signed shift right
ushr Performs unsigned shift right
– Example
fun main(args:  Array<String>) {

	var a = 10
	var b = 20

	var c = a.and(b);
	var d = a.or(b)
	var e = a.xor(b)
	var f = a.inv()
	var g = a.shl(b)
	var h = a.shr(b)
	var i = a.ushr(b)

	println("a = $a, b = $b")
	println("c = $c")
	println("d = $d")
	println("e = $e")
	println("f = $f")
	println("g = $g")
	println("h = $h")
	println("i = $i")
} 

When you run the program, you will get below output:

a = 10, b = 20
c = 0
d = 30
e = 30
f = -11
g = 10485760
h = 0
i = 0

6. Kotlin ‘In’ operators

There are some pre-defined operators in kotlin that can be used to check whether an object is present in the collection or not. They are –

Operators Expression Equivalent to Description
in a in b b.contains(a) Checks whether b contains a
!in a !in b !b.contains(a) Checks whether b does not contain a
– Example
fun main(args:  Array<String>) {

	val marks = intArrayOf(10, 12, 14, 16, 18, 20, 21, 22, 23, 25)
	var a = 13
	var b = 18
	if (a in marks) {
    		println("marks contains $a")
	} else {
    		println("marks does not contains $a")
	}

	if (b in marks) {
    		println("marks contains $b")
	} else {
    		println("marks does not contains $b")
	}
} 

When we run the program, you will get below output:

marks does not contains 13
marks contains 18




7. Kotlin Indexed Access Operators

Indexed access operators in kotlin can be used to perform actions on arrays. You can get value of element present at particular index, change it’s value etc.

Below are list of indexed access operators in kotlin –

Expression Equivalent to
a[i] a.get(i)
a[i, n] a.get(i, n)
a[i_1, i_2, …, i_n] a.get(i_1, …, i_n)
a[i] = b a.set(i, b)
a[i, j] = b a.set(i, j, b)
a[i_1, …, i_n] = b a.set(i_1, …, i_n, b)

Square brackets are translated to calls to get and set with appropriate numbers of arguments.

– Example
fun main(args:  Array<String>) {

   val marks = intArrayOf(10, 12, 14, 16, 18, 20, 21, 22, 23, 25)
   var i = 3	

   println(marks[i])	
} 

When you run the program, you will get below output:

16

8. Kotlin Unary Prefix Operators

As the name suggests, these operators are used on single operand as prefix.

Below are lists of unary prefix operators in kotlin.

Operators Expression Equivalent to Description
+ +a a.unaryPlus() Unary plus
-a a.unaryMinus() Unary minus
! !a a.not() NOT (It inverts the value)
– Example
fun main(args:  Array<String>) {

	var a = 14
	var e = false

	var b = +a
	var c = -a
	var d = !e

	println("b = $b")
	println("c = $c")
	println("d = $d")
} 

When you run the program, you will get below output:

b = 14
c = -14
d = true




9. Kotlin Invoke Operators

Below are list of invoke operators in kotlin:

Expression Equivalent to
a() a.invoke()
a(i) a.invoke(i)
a(i1, i2, …, in) a.inkove(i1, i2, …, in)
a[i] = b a.set(i, b)

Parentheses are translated to calls to invoke with appropriate number of arguments.

Conclusion

In this post, we have seen what are different types of operators in kotlin. You can use any operator as per you need. However, we have also seen that there are no bitwise operators in kotlin. You must use pre-defined functions in-order to perform bit related action.

Now, what next?
In the next post, you will learn about control flows in kotlin.

Leave a Reply