Kotlin Operator Overloading

Operator overloading are special concept to provides new meaning to existing operator without lose the operator original behaviour. that is normally exist in all modern programming language. kotlin programming also support this features.

Kotlin : Example Assignments Operator Overloading

In this section given example how to overload Assignment operators in kotlin programming. there is five function are available to overload (+=,-=,*=,/=,%=) this operators.

for example assume that there is two different objects objA and objB are same properties that is x (integer data type).

Function Overview Execution Short Form
plusAssign() Addition and assign (+=) objA.plusAssign(objB) objA+=objB
minusAssign() Subtract and assign (-=) objA.minusAssign(objB) objA-=objB
timesAssign() Multiplication and assign (*=) objA.timesAssign(objB) objA*=objB
divAssign() Divide and assign (/=) objA.divAssign(objB) objA/=objB
remAssign() remainder and assign (%=) objA.remAssign(objB) objA%=objB

Overload += operators

class Assignments(var x:Int){
    //definition of assignment operator overload
    operator fun plusAssign(other:Assignments):Unit{ x+=other.x}
}
fun main(args: Array<String>){
    //make two object
    var objA=Assignments(3)
    var objB=Assignments(9)
    
    println("Before objA.x = ${objA.x}  objB.x = ${objB.x}")
    
    objA+=objB //add and assign

    println("After  objA.x = ${objA.x} objB.x = ${objB.x}")
    
    println("Alternatives")
    var objC=Assignments(3)
    var objD=Assignments(9)
    println("Before objC.x = ${objC.x}  objD.x = ${objD.x}")
    objC.plusAssign(objD) //add and assign
    println("After  objC.x = ${objC.x} objD.x = ${objD.x}")
   
    
}

Output

Before objA.x = 3  objB.x = 9
After  objA.x = 12 objB.x = 9
Alternatives
Before objC.x = 3  objD.x = 9
After  objC.x = 12 objD.x = 9

Overload -= operators

class Assignments(var x:Int){
    //definition of assignment operator overload
    operator fun minusAssign(other:Assignments){ x-=other.x}
}
fun main(args: Array<String>){
    //make two object
    var objA=Assignments(8)
    var objB=Assignments(5)
    
    println("Before objA.x = ${objA.x}  objB.x = ${objB.x}")
    
    objA-=objB //Subtract and assign

    println("After  objA.x = ${objA.x}  objB.x = ${objB.x}")
    
    println("Alternatives")
    var objC=Assignments(8)
    var objD=Assignments(5)
    println("Before objC.x = ${objC.x}  objD.x = ${objD.x}")
    objC.minusAssign(objD) //Subtract and assign
    println("After  objC.x = ${objC.x}  objD.x = ${objD.x}")
   
    
}

Output

Before objA.x = 8  objB.x = 5
After  objA.x = 3  objB.x = 5
Alternatives
Before objC.x = 8  objD.x = 5
After  objC.x = 3  objD.x = 5

That Similar concept overload of other assignments operators. See this examples.

class Assignments(var x:Int){
    //definition of assignment operator overload
    operator fun plusAssign(other:Assignments):Unit{ x+=other.x}
    operator fun minusAssign(other:Assignments):Unit{ x-=other.x}
    operator fun timesAssign(other:Assignments):Unit{ x*=other.x}
    operator fun divAssign(other:Assignments):Unit{ x/=other.x}
    operator fun remAssign(other:Assignments):Unit{ x%=other.x}
    
    fun before(operation:String =" " ,other:Assignments){
        println("\nBefore $operation $x   ${other.x} ")
    }
    fun after(operation:String =" " ,other:Assignments){
        println(" After $operation $x   ${other.x} ")
    }
 
}
fun main(args: Array<String>){
    //make two object
    var objA=Assignments(3)
    var objB=Assignments(9)
    
    objA.before("[objA+=objB] = ",objB)
    
    objA+=objB //add and assign
    
    objA.after("[objA+=objB] = ",objB)
    
    
    var objC=Assignments(2)
    var objD=Assignments(5)
    
    objC.before("[objC-=objD] = ",objD)
    
    objC-=objD //minus and assign
    
    objC.after("[objC-=objD] = ",objD)
    
    var objE=Assignments(6)
    var objF=Assignments(3)
    
    objE.before("[objE*=objF] = ",objF)
    
    objE*=objF //times and assign
    
    objE.after("[objE*=objF] = ",objF)
    
    
    var objG=Assignments(8)
    var objH=Assignments(2)
    
    objG.before("[objG/=objH] = ",objH)
    
    objG/=objH //div and assign
    
    objG.after("[objG/=objH] = ",objH)
    
    
    var objI=Assignments(6)
    var objJ=Assignments(4)
    
    objI.before("[objI/=objJ] = ",objJ)
    
    objI%=objJ //% and assign
    
    objI.after("[objI/=objJ] = ",objI)
    
    
    
}

Output


Before [objA+=objB] =  3   9 
 After [objA+=objB] =  12   9 

Before [objC-=objD] =  2   5 
 After [objC-=objD] =  -3   5 

Before [objE*=objF] =  6   3 
 After [objE*=objF] =  18   3 

Before [objG/=objH] =  8   2 
 After [objG/=objH] =  4   2 

Before [objI/=objJ] =  6   4 
 After [objI/=objJ] =  2   2 

Example --,++ Operator Overloading

class Modifier(var x:Int){

    operator fun inc()=Modifier(++x)
    operator fun dec()=Modifier(--x)
}
fun main(args: Array<String>){
    //make two object
    var obj1=Modifier(10)
    var obj2=Modifier(10)
    
    println(" Initial (obj1,obj2): ${obj1.x} ${obj2.x}")
    ++obj1
    --obj2
    println(" After (++obj1,--obj2) : ${obj1.x} ${obj2.x}")
    
    obj1++
    obj2--
    println(" After (obj1++,obj2--) : ${obj1.x} ${obj2.x}")
   
}

Output

 Initial (obj1,obj2): 10 10
 After (++obj1,--obj2) : 11 9
 After (obj1++,obj2--) : 12 8

Example Arithmetic operators

This is similar to first example.

Function Execution Short Form
plus() objA.plus(objB) objA+objB
minus() objA.minus(objB) objA-objB
times() objA.times(objB) objA*objB
div() objA.div(objB) objA/objB
rem() objA.rem(objB) objA%objB
/*Arithmetic Operator overload*/
class Arithmetic(var operands:Int=0) {
    
    operator fun plus(other:Arithmetic) : Number{
        return operands+other.operands
    }
    operator fun minus(other:Arithmetic) : Number{
        return operands-other.operands
    }
    
    operator fun times(other:Arithmetic) : Number{
        return operands * other.operands
    }
     operator fun div(other:Arithmetic) : Number{
        if(other.operands==0) return 0 
        return operands/other.operands
    }
    operator fun rem(other:Arithmetic) : Number{
        return operands%other.operands
    }
}


fun main(args: Array<String>) {
 
    val obj1=Arithmetic(5)
    val obj2=Arithmetic(3)
    
    println("Basic Method")
    //overload Arithmetic operators
    println(obj1+obj2)
    println(obj1-obj2)
    println(obj1*obj2)
    println(obj1/obj2)
    println(obj1%obj2)
    
    println("Other Method")
    println(obj1.plus(obj2))
    println(obj1.minus(obj2))
    println(obj1.times(obj2))
    println(obj1.div(obj2))
    println(obj1.rem(obj2))
    
}

Output

Basic Method
8
2
15
1
2
Other Method
8
2
15
1
2

Example Comparison operators

class Comparison(var operands:Int){
   
    operator fun compareTo(other:Comparison):Int{
        if(operands >(other.operands)) return 1
        else return 0   
    }
   
}

fun main(args: Array<String>) {
 
    val setA=Comparison(40)
    val setB=Comparison(20)
    if(setA>setB){
        println("Set A Is Win")
    }else{
        println("Set B Is Win")
    }
}
Set A Is Win

Example Invoke operator overloading

class Money(val price:Number=50000){
    
    //Invoke of none parameter 
    operator fun invoke(): Number =price
    //Invoke of one number parameters 
    operator fun invoke(discount:Number)=println("Price: $price Discount :$discount")
    
    //Invoke of two parameters 
    operator fun invoke(discount:Number,typeInfo:String){
        println("Price :$price Discount :$discount  Type = $typeInfo")
    }
}

fun main(args: Array<String>) {
   val set1=Money()
    
   println(set1()) //50000
   
   set1(1000) 
   set1(2000)
   set1(3000,"Special User") 
 
}

Output

50000
Price: 50000 Discount :1000
Price: 50000 Discount :2000
Price :50000 Discount :3000  Type = Special User

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved