Author: saqibkhan

  • Kotlin Operator

    Operators are special characters which perform operation on operands (values or variable).There are various kind of operators available in Kotlin.

    • Arithmetic operator
    • Relation operator
    • Assignment operator
    • Unary operator
    • Bitwise operation
    • Logical operator

    Arithmetic Operator

    Arithmetic operators are used to perform basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/) etc.

    OperatorDescriptionExpressionTranslate to
    +Additiona+ba.plus(b)
    Subtractiona-ba.minus(b)
    *Multiplya*ba.times(b)
    /Divisiona/ba.div(b)
    %Modulusa%ba.rem(b)

    Example of Arithmetic Operator

    fun main(args : Array<String>) {  
    
    var a=10;  
    
    var b=5;  
    
    println(a+b);  
    
    println(a-b);  
    
    println(a*b);  
    
    println(a/b);  
    
    println(a%b);  
    
    }

    Output:

    15
    5
    50
    2
    0
    

    Relation Operator

    Relation operator shows the relation and compares between operands. Following are the different relational operators:

    OperatorDescriptionExpressionTranslate to
    >greater thana>ba.compateTo(b)>0
    <Less thana<ba.compateTo(b)<0
    >=greater than or equal toa>=ba.compateTo(b)>=0
    <=less than or equal toa<=ba?.equals(b)?:(b===null)
    ==is equal toa==ba?.equals(b)?:(b===null)
    !=not equal toa!=b!(a?.equals(b)?:(b===null))

    Example of Relation Operator

    fun main(args : Array<String>) {  
    
        val a = 5  
    
        val b = 10  
    
        val max = if (a > b) {  
    
            println("a is greater than b.")  
    
            a  
    
        } else{  
    
            println("b is greater than a.")  
    
            b  
    
        }  
    
        println("max = $max")  
    
    }  

      Output:

      b is greater than a.
      max = 10
      

      Assignment operator

      Assignment operator “=” is used to assign a value to another variable. The assignment of value takes from right to left.

      OperatorDescriptionExpressionConvert to
      +=add and assigna+=ba.plusAssign(b)
      -=subtract and assigna-=ba.minusAssign(b)
      *=multiply and assigna*=ba.timesAssign(b)
      /=divide and assigna/=ba.divAssign(b)
      %=mod and assigna%=ba.remAssign(b)

      Example of Assignment operator

      fun main(args : Array<String>) {  
      
        
      
          var a =20;var b=5  
      
          a+=b  
      
          println("a+=b :"+ a)  
      
          a-=b  
      
          println("a-=b :"+ a)  
      
          a*=b  
      
          println("a*=b :"+ a)  
      
          a/=b  
      
          println("a/=b :"+ a)  
      
          a%=b  
      
          println("a%=b :"+ a)  
      
        
      
      } 

        Output:

        a+=b :25
        a-=b :20
        a*=b :100
        a/=b :20
        a%=b :0
        

        Unary Operator

        Unary operator is used with only single operand. Following are some unary operator given below.

        OperatorDescriptionExpressionConvert to
        +unary plus+aa.unaryPlus()
        unary minus-aa.unaryMinus()
        ++increment by 1++aa.inc()
        decrement by 1–aa.dec()
        !not!aa.not()

        Example of Unary Operator

        fun main(args: Array<String>){  
        
            var a=10  
        
            var b=5  
        
            var flag = true  
        
            println("+a :"+ +a)  
        
            println("-b :"+ -b)  
        
            println("++a :"+ ++a)  
        
            println("--b :"+ --b)  
        
            println("!flag :"+ !flag)  
        
        }  

          Output:

          +a :10
          -b :-5
          ++a :11
          --b :4
          !flag :false
          

          Logical Operator

          Logical operators are used to check conditions between operands. List of logical operators are given below.

          OperatorDescriptionExpressionConvert to
          &&return true if all expression are true(a>b) && (a>c)(a>b) and (a>c)
          ||return true if any expression are true(a>b) || (a>c)(a>b) or(a>c)
          !return complement of expression!aa.not()

          Example of Logical Operator

          fun main(args: Array<String>){  
          
              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
            

            Bitwise Operation

            In Kotlin, there is not any special bitwise operator. Bitwise operation is done using named function.

            Named FunctionDescriptionExpression
            shl (bits)signed shift lefta.shl(b)
            shr (bits)signed shift righta.shr(b)
            ushr (bits)unsigned shift righta.ushr(b)
            and (bits)bitwise anda.and(b)
            or (bits)bitwise ora.or(b)
            xor (bits)bitwise xora.xor(b)
            inv()bitwise inversea.inv()

            Example of Bitwise Operation

            fun main(args: Array<String>){  
            
                var a=10  
            
                var b=2  
            
              
            
                println("a.shl(b): "+a.shl(b))  
            
                println("a.shr(b): "+a.shr(b))  
            
                println("a.ushr(b:) "+a.ushr(b))  
            
                println("a.and(b): "+a.and(b))  
            
                println("a.or(b): "+a.or(b))  
            
                println("a.xor(b): "+a.xor(b))  
            
                println("a.inv(): "+a.inv())  
            
              
            
            } 

              Output:

              a.shl(b): 40
              a.shr(b): 2
              a.ushr(b:) 2
              a.and(b): 2
              a.or(b): 10
              a.xor(b): 8
              a.inv(): -11
              
            1. Lack of Full Support for Distributed Training (Standalone Keras)

              • Distributed training capabilities, while available in TensorFlow 2.x’s Keras API, are not as robust in standalone Keras. This can be a limitation for those needing to train models on multi-GPU or multi-node systems in large-scale production environments.
            2. Kotlin Type Conversion

              Type conversion is a process in which one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For example Int cannot be assigned into Long or Double.

              In Java

              int value1 = 10;  
              
              long value2 = value1;  //Valid code   

                In Kotlin

                  var value1 = 10  
                val value2: Long = value1  //Compile error, type mismatch 

                  However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function.

                  var value1 = 10  
                  
                  val value2: Long = value1.toLong()  

                    The list of helper functions used for numeric conversion in Kotlin is given below:

                    • toByte()
                    • toShort()
                    • toInt()
                    • toLong()
                    • toFloat()
                    • toDouble()
                    • toChar()

                    Kotlin Type Conversion Example

                    Let see an example to convert from Int to Long.

                    fun main(args : Array<String>) {  
                    
                        var value1 = 100  
                    
                        val value2: Long =value1.toLong()  
                    
                        println(value2)  
                    
                    } 

                      We can also converse from larger data type to smaller data type.

                      fun main(args : Array<String>) {  
                      
                          var value1: Long = 200  
                      
                          val value2: Int =value1.toInt()  
                      
                          println(value2)  
                      
                      }
                    1. Less Popular for Research

                      • Research Preference: Many cutting-edge research models are implemented in PyTorch or TensorFlow rather than Keras, as these frameworks offer more flexibility for developing novel architectures and experimenting with custom training procedures. As a result, Keras may not be the best choice for researchers pushing the boundaries of machine learning.
                    2. Performance on Large-Scale Systems

                      • Keras may not be the most optimized choice for large-scale deep learning systems where every bit of performance matters, especially when comparing to lower-level frameworks like TensorFlow or PyTorch, which allow better control over resource management and optimization.
                    3. Dependency on Backends

                      • Backend Complexity: Since Keras relies on other backends like TensorFlow or Theano, users are sometimes required to have knowledge of these backends to solve performance issues or low-level bugs. This can complicate the usage for users who expect Keras to handle everything without backend-specific adjustments.
                    4. Kotlin Data Type

                      Data type (basic type) refers to type and size of data associated with variables and functions. Data type is used for declaration of memory location of variable which determines the features of data.

                      In Kotlin, everything is an object, which means we can call member function and properties on any variable.

                      Kotlin built in data type are categorized as following different categories:

                      • Number
                      • Character
                      • Boolean
                      • Array
                      • String

                      Number Types

                      Number types of data are those which hold only number type data variables. It is further categorized into different Integer and Floating point.

                      Data TypeBit Width (Size)Data Range
                      Byte8 bit-128 to 127
                      Short16 bit-32768 to 32767
                      Int32 bit-2,147,483,648 to 2,147,483,647
                      Long64 bit-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
                      Float32 bit1.40129846432481707e-45 to 3.40282346638528860e+38
                      Double64 bit4.94065645841246544e-324 to 1.79769313486231570e+308

                      Character (Char) Data Type

                      Characters are represented using the keyword Char. Char types are declared using single quotes (”).

                      Data TypeBit Width (Size)Data Range
                      Char4 bit-128 to 127

                      Example

                      val value1 = 'A'  
                      
                      //or  
                      
                      val  value2: Char  
                      
                      value2= 'A'  

                        Boolean Data Types

                        Boolean data is represented using the type Boolean. It contains values either true or false.

                        Data TypeBit Width (Size)Data Value
                        Boolean1 bittrue or false

                        Example

                        1. val flag = true  

                        Array

                        Arrays in Kotlin are represented by the Array class. Arrays are created using library function arrayOf() and Array() constructor. Array has get (), set() function, size property as well as some other useful member functions.

                        Creating Array using library function arrayOf()

                        The arrayOf() function creates array of wrapper types. The item value are passed inside arrayOf() function like arrayOf(1,2,3) which creates an array[1,2,3].

                        The elements of array are accessed through their index values (array[index]). Array index are start from zero.

                        val id = arrayOf(1,2,3,4,5)  
                        
                        val firstId = id[0]  
                        
                        val lasted = id[id.size-1] 

                          Creating Array using Array() constructor

                          Creating array using Array() constructor takes two arguments in Array() constructor:

                          1. First argument as a size of array, and
                          2. Second argument as the function, which is used to initialize and return the value of array element given its index.
                          val asc = Array(5, { i -> i * 2 }) //asc[0,2,4,6,8]  

                            String

                            String in Kotlin is represented by String class. String is immutable, which means we cannot change the elements in String.

                            String declaration:

                            val text ="Hello, JavaTpoint"  

                            Types of String

                            String are categorize into two types. These are:

                            1. Escaped String: Escape String is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.

                            val text1 ="Hello, JavaTpoint"  
                            
                            //or  
                            
                            val text2 ="Hello, JavaTpoint\n"  
                            
                            //or  
                            
                            val text3 ="Hello, \nJavaTpoint" 

                              2. Raw String: Row String is declared within triple quote (“”” “””). It provides facility to declare String in new lines and contain multiple lines. Row String cannot contain any escape character.

                              val text1 ="""  
                              
                                           Welcome   
                              
                                               To  
                              
                                         JavaTpoint  
                              
                                  """
                            1. Limited Deployment Flexibility (Standalone Keras)

                              • Before TensorFlow 2 Integration: When Keras was used as a standalone library before its integration into TensorFlow, deploying models to production was more challenging. Although this has been improved with Keras’ inclusion in TensorFlow, standalone Keras may still have limitations in terms of deployment tools and pipelines compared to frameworks like TensorFlow and PyTorch.
                            2. Lack of Support for Dynamic Computation Graphs

                              • Static Graphs: Keras, particularly when using TensorFlow as a backend, primarily supports static computation graphs (also known as “Define-and-Run” models). This can be limiting for models that require dynamic computation graphs, where the structure of the graph changes during runtime. PyTorch, which uses dynamic graphs (“Define-by-Run”), is better suited for such models.
                            3. Limited Support for Low-Level Operations

                              • Complex Custom Operations: For advanced research or cutting-edge models, if you need to perform custom mathematical operations or manipulate tensors at a low level, Keras may not be as efficient or flexible. In contrast, PyTorch or TensorFlow (using their low-level APIs) allows for greater control in implementing novel operations.