Kotlin program to demonstrate the operator overloading. Either used in postfix or prefix notation these functions work well in both the cases, with the same expected output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class IncDecOverload(var str:String) { // overloading increment function operator fun inc(): IncDecOverload { val obj = IncDecOverload(this.str) obj.str = obj.str + 'a' return obj } // overloading decrement function operator fun dec(): IncDecOverload { val obj = IncDecOverload(this.str) obj.str = obj.str.substring(0,obj.str.length-1) return obj } override fun toString(): String { return str } } // main function fun main(args: Array<String>) { var obj = IncDecOverload("Hello") println(obj++) println(obj--) println(++obj) println(--obj) } |
Program Output:
1 2 3 4 | Hello Helloa Helloa Hello |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.