Ronnie Atuhaire's Blog 😎

Ronnie Atuhaire's Blog 😎

Kotlin Operators

Kotlin Operators

Subscribe to my newsletter and never miss my upcoming articles

Hello there 👋, welcome back to my blog! In the previous article, we learnt about the different data types that we have in the Kotlin language. Today, we shall learn the various operators that are in use and a very helpful topic to learn about in any programming language.

So what are operators? image.png In computer programming, operators are constructs defined within programming languages that behave generally like functions, but which differ syntactically or semantically.

Basically, an operator in a programming language is a symbol that tells the compiler or interpreter to perform the specific mathematical, relational or logical operation and produce the final result.

Operators are the constructs that can manipulate the value of operands as we see in the picture above.

image.png Just like Python, Kotlin operators are much the same except with a few differences we shall see. There are various kinds of operators available in Kotlin and in this tutorial, we shall learn the following:

🔼 Arithmetic operators
🔼 Relation operators
🔼 Assignment operators
🔼 Unary operators
🔼 Bitwise operators
🔼 Logical operators
🔼 Other operators

🔹 Arithmetic operators

Arithmetic operators are used to performing basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/) etc. Refer to the table below:

image.png As we can see, in Python we have an extra ** for Exponentiation and // for Floor division.

The translate section tells us what exactly happens under the hood. They are actually functions.

Try Running this at Kotlin playground

fun main() {

    val number1 = 12.5
    val number2 = 3.5
    var result: Double

    result = number1 + number2
    println("number1 + number2 = $result")

    result = number1 - number2
    println("number1 - number2 = $result")

    result = number1 * number2
    println("number1 * number2 = $result")

    result = number1 / number2
    println("number1 / number2 = $result")

    result = number1 % number2
    println("number1 % number2 = $result")
}

NOTE: The + operator is also used for the concatenation of String values.

val myStart = "Kotlin "
val myMiddle = "For"
val myEnd = "Python Developers"

val finalText = myStart + myMiddle + myEnd

println(finalText) //-> Kotlin For Python Developers

🔹 Relation operators

Relation operator shows the relation and compares between operands. Refer to the table below for more information.

image.png These can also be called comparison and equality operators. They are used in control flow such as if expression, when expression, and loops.

In Python language, we do have exactly the same operators.

fun main() {

    val firstNum = 20
    val secondNum = 30
    if (firstNum == secondNum){
        println("These numbers are equal")
    } else if (firstNum > secondNum){
        println("Seems the first number is bigger!")
    } else {
        println("Second number is greater!")
    }
}

We shall look more at expressions in later chapters. The above program helps in finding the maximum value and we have only implemented two operators.

🔹 Assignment operators

Assignment operators are used to assign value to a variable. We have already used simple assignment operator = before.

image.png We have the exact implementations in Python..

Try this:

fun main() {
    var numOne = 30
    var numTwo = 40
    var numThree = 10

    numOne *= 5   // same as  numOne =  numOne * 5
    numTwo /= numThree // same as numTwo =  numTwo / numThree
    numThree += numTwo // same as numThree = numThree + numTwo

    println("$numOne") // -> 150
    println("$numTwo") // -> 4
    println("$numThree") // -> 14
}

🔹 Unary operators

A unary operator is used with only a single operand. Following are some unary operators available in Kotlin. image.png

Apart from the rest, in Python, we do not have increment and decrement operators.

Try This:

fun main(){  
    var a=10  
    var b=5  
    var flag = true 

    println("+a :"+ +a) // positive ten -> 10 
    println("-b :"+ -b)  // negative Five -> -5
    println("++a :"+ ++a)  // increments 10 to 11 by 1
    println("--b :"+ --b)  // reduces 5 to 4 by 1
    println("!flag :"+ !flag)  // returns opposite -> false
}

Note: The -- and ++ can sometimes be referred under arithmetic operators which is still okay since they do perform mathematical calculations.

🔹Bitwise operators

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.

Unlike Python or Java, there are no bitwise and bitshift operators in Kotlin. To perform these tasks, various functions (supporting infix notation) are used:

Table ->Implimentations [Python Vs Kotlin]

image.png

Kotlin-Only Bitwise Table image.png

Note: Bitwise and bit shift operators are used on only two integral types (Int and Long) to perform bit-level operations.

To understand these operations, you need to know binary! For example:

12 => 00001100 (In Binary)
25 => 00011001 (In Binary)

Bitwise OR Operation of 12 and 25
   00001100 or
   00011001
   __________
   00011101  => 29 (In decimal)

It's basically checking if there is a 0 or 1 in the operation. Either of the operands should be 1 to return 1 in as the result!

Try this:

fun main() {

    val number1 = 12
    val number2 = 25
    val result: Int

    result = number1 or number2   // same as -> result = number1.or(number2)
    println(result)
}

Recommended Reading Bitwise By Programiz

🔹 Logical operators

Logical operators are used for checking conditions between operands. A list of logical operators is given below.

image.png They are basically two operations here, || ->true if either of the Boolean expression is true and && ->true if all Boolean expressions are true

Try this.

fun main(){  
    var a=10  
    var b=5  
    var c=15  
    var flag = false  
    var result: Boolean  
    result = (a>b) && (a>c)  
    println("(a>b) && (a>c) :"+ result)  
    result = (a>b) || (a>c)  
    println("(a>b) || (a>c) :"+ result)  
    result = !flag  
    println("!flag :"+ result)  

}

Output:

(a>b) && (a>c) :false
(a>b) || (a>c) :true
!flag :true

🔹Other operators

Python has identity and membership operators. Kotlin has some of these operators which are very helpful:

🔸The in Operator
◽ specifies the object being iterated in a for loop.
◽ is used as an infix operator to check that a value belongs to a range, a collection or another entity that defines the 'contains' method.
◽ used in when expressions for the same purpose.
◽ marks a type parameter as contravariant.

fun main(args: Array<String>) {

    val numbers = intArrayOf(1, 4, 42, -3)

    if (4 in numbers) {
        println("numbers array contains 4.")
    }

🔸The !in Operator
◽ is used as an operator to check that a value does NOT belong to a range, a collection or another entity that defines the 'contains' method.
◽ is used in when expressions for the same purpose

fun main(args: Array<String>) {

    val numbers = intArrayOf(1, 4, 42, -3)

    if (2 !in numbers) {
        println("numbers array does not contain 2.")
    }
}

🔸The is Operator
◽ checks that a value has a certain type
◽ is used in when expressions for the same purpose

if (obj is String) {
    println(obj.length)
}

🔸The !is Operator
◽ checks that a value does NOT have a certain type
◽ is used in when expressions for the same purpose

if (obj !is String) {
    println(obj.length)
}

To understand the next operators, you need to know what casting is.

Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. image.png

Python avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.

In Type Casting, loss of data may occur as we enforce the object to a specific data type.

🔸The as Operator
◽ is used for type casts ◽ specifies an alias for an import

Usually, the cast operator throws an exception if the cast isn't possible. And so, it's called unsafe. The unsafe cast in Kotlin is done by the infix operator as.

val x: String = y as String

Note that null cannot be cast to String, as this type is not nullable. If y is null, the code above throws an exception. To make code like this correct for null values, use the nullable type on the right-hand side of the cast:

🔸The as? Operator
◽ is used for safe type casts To avoid exceptions, use the safe cast operator as?, which returns null on failure.

val x: String? = y as? String

Kotlin is, !is, as and as? explained in one pic.

image.png

Read more about type checks and casts on the official docs.

🔸The [ ] Operator [Index access Operator]
The Subscript or Array Index Operator is denoted by [ ]. This operator is generally used with arrays to retrieve and manipulate the array.

Here are some expressions using the index access operator with corresponding functions in Kotlin. image.png

We can also use the same access operator to modify lists. Try:

fun main() {

    val myArray  = intArrayOf(1, 2, 3, 4, - 1)

    println(myArray[1])   // -> 2

    myArray[1]= 12 // modify

    println(myArray[1]) // ->4
}

🔸The ( ) Operator (Invoke Operator)
Unlike Python, an interesting feature of the Kotlin language is the ability to define an "invoke operator". Here are some expressions using invoke operator with corresponding functions in Kotlin.

image.png

In Python & Kotlin, parenthesis are translated to call invoke member functions and we have been using them all day long.

fun myFunction( ){
     // body ....
}

fun main ( ){
    println(myFunction())
}

🔸The ? : Operator (Elvis Operator)
The Elvis operator in Kotlin is an operator that receives two inputs and returns the first argument if it is non-null or the second one otherwise.

fun main(){  

var str: String? = null  
var str2: String? = "May be declare nullable string"  
var len1:  Int = str ?.length ?: -1  
var len2:  Int = str2 ?.length ?:  -1  

println("Length of str is ${len1}")  
println("Length of str2 is ${len2}")  
}

It is fancily called the null coalescing operator. It is a variant of the ternary operator but for null-safety checking.

Read more about Elvis Operators here

Conclusion 📋

In this tutorial, we have learnt the different operators that are available in the Kotlin language. We made some comparisons with Python and I believe you are now capable of performing some mathematical calculations in Kotlin.

If you enjoyed this tutorial, consider subscribing and following me here 😊!

Let's connect on Twitter with ❤

Ronnie Atuhaire 😎

 
Share this