Kotlin Operator Overloading
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
Operator Overloading allows us to overload operators for our Custom Classes.
Let us say we have a Complex class to represent Complex numbers.
And we want to add two Complex numbers.
Or lets say we want to subtract two Complex numbers.
We would rather use + operator or - operator to add or subtract complex numbers.
Example:
var C1 = Complex(1, 3)
var C2 = Complex(2,4)
var C3 = C1 + C2
var C4 = C2 - C1
Let us see how we can create a Complex class and then overload plus and minus operator to achieve our goal.class Complex(val real: Int, val imaginary: Int)
{
operator fun plus(c: Complex): Complex
{
return Complex(real + c.real, imaginary + c.imaginary)
}
operator fun minus(c: Complex): Complex
{
return Complex(real - c.real, imaginary - c.imaginary)
}
override fun toString(): String
{
return this.real.toString() + " + " + this.imaginary.toString() + "i"
}
}
fun main(args: Array<String>)
{
var C1 = Complex(1,3)
var C2 = Complex(2,4)
var C3 = C1 + C2
var C4 = C2 - C1
println(C3)
println(C4)
}
Output:
3 + 7i
1 + 1i