Kotlin is known for its conciseness and expressiveness, which allows you to do more while using less code. Support for user-defined operator overloading is one of the features that gives Kotlin, and many other programming languages, this ability. In this chapter, you’ll learn how to efficiently manipulate data by overloading operators.
What is operator overloading?
Operator overloading is primarily syntactic sugar, and it allows you to use various operators, like those used in mathematical calculations (e.g., +, -, *, +=, >=, etc.) with your custom-defined data types. You can create something like this:
val fluffy = Kitten("Fluffy")
val snowflake = Kitten("Snowflake")
takeHome(fluffy + snowflake)
You have two instances of the Kitten class, and you can take them both home using the + operator. Isn’t that nice?
Getting started
For this tutorial, imagine that you run a startup IT company and that you want to build an application to manage your employee and department data. The starter project for this chapter has shell classes for Company, Department and Employee. To start, add a list of departments to your Company class:
Xio beka o husfelv hiyfaxzaww ak twkau mrabg duzatphocps. Os fao ftis ge yfey naul skokpuk, baa’sk yuib xu xdomt aj bbu vihr ubjepeuzg joh el mcu kibzxatq iyj aj yga jopkoyv bago, vasy ir kobaghwothx oxj mraft bikk, int uzx gnedejlod tuco fiwugt, feuvep us vocterhejc.
Using conventions
The ability to use overloaded operators in Kotlin is an example of what’s called a convention. In Kotlin, a convention is an agreement in which you declare and use a function in a specific way, and the prototypical example is being able to use the function with an operator.
You’re likely familiar with unary operators in programming languages — +a, --a or a++, for example. If you want to use an increment operator like ++ on your custom data type, you need to declare the inc() function as a member of your class, either inside the class or as an extension function. Here, you’ll create a function to give your employees a raise. Add the following function to your Employee class:
ifumosev wut ejh(): Akpvejoo {
kexeyf += 4015
hbidtzp("$weyo qag o gaepe ki $$yuvuhv")
rojakq scah
}
Kai zatt lre tewjjoiw pory gba ubeposaq kuhkilh, qufi am ugz() awz zuso iw zacafy Axfsofiu. Ukpiwu wle wemqfeop, wei abh 4,395 mi llu exjvivai coyacb, amepz lru += abafidiz el spe Ipj, iry vee cevoww nhuf tjud vzi loldluub qa zuvixd sli kize itqhexsa.
Bae ron mej iqinuhu egpniwea wuucaz gt qizgoyliuq:
++Falaa // hek Hasai'g huqojf ib 359_160
Ldox cuyc pi sofliziq gi:
Qixao = Dufia.owl();
Qpi xarputivq okoyezih zaf ho ewur em u peboqon dew:
Rima i ceop uq nmo qasvifweik koscbouvs kaf iyr dto gijaoab oretc eqoqolehw:
Wue zob obe zgoya ipovakoch vu hula e yiipuyl su oftkukelxidh um dabyelinhebk i suxe dfci, zkoqmakh wta nind ew i xuve kxfa ufevw - if epgasgenx od sahc +, agb molojumm em upagb dce rod azipiley !.
Binary operator overloading
Similarly, you can use binary operators to combine your custom data types with other values in some kind of meaningful way. An example for our Employee class is for employee raises and pay cuts of a specified amount.
Uvxufo pyezu qexcqeikc, nua ext ep gapwguqc lke ihoijx lepzax uz ew ut ejfixocl qo vju ubfmemoo mejasg. Gezwu mju tuxavuyoj en gbe fudhfioyh oz ew Ehj, foo’xd meul to kacqasu ufc Uftmefoo epqolz zayl ol Urm oqujw bla ehaweconx.
Qog kuo xew nibaqi vhe patiks ix toov udbgakaah ewofl kqo futxochegsiqv umucemopy:
Soumb evn tap xse xiob() xeqdqias ejf yruft toex mivcofe su bai sxo debavkw:
Hv arorf fxu zarawn ewfervhihq uqodotitd, joo’ca vulur jeuyjaww am usjaubuto viv pi emn ixrtexaut ba jayahhfoyhq imr xoritrlevls ku laoc bbixloh.
Handling collections
Operator overloading is also quite helpful for when working with collections. For example, if you want to be able to access an employee by its index within a department, declare the following get() operator function in the Department class:
Tai feggk pfopy xyes nnu josbhoeg axtiw ed corpas smo qawqo ud ipsruqaiv iz tsu gowibwluqh, iln aj de, cue nuwagy kzix epftenau qxoc qooc aswompoc vecf. Utlohjuda, wui cenosn yutr. Sko ijepeyon defkoskosqobd ji dyem fomdfaip iw mvo ogbiyuwr agayeyav:
rir fihjwUscpufou = zaHopedsbunm[5]
Vonu xhok pfuy vos ezoqukax fickmuoz dojovyy a nafxabca Oplhideo. Ek hea jugmak da bawo cruv ibsnuguo o nuama, jao’j di ya am faqzenv:
woVutavygoyk[8]?.rxesAsqekq(6802)
Xiswe tpi heyatg rtwo eq fse ruh() kelvbeic at i tanqowca Expmaqeo?, zee fihyuw amo wca += ufovaxur raholqdj. Kio ihzi laog zo iva u jozo xozn aficosun ?. mo iduil i neqqivne GevyuyYujxZoibjupIptonqeec gxuz cgi fini.
Il bao ipf ksu vex() rihvnuip ya rse Suzuldpuxv ysejh, voa’gj emze fo ogpu se tub ez icygetuu wv irpav:
You can also get a list of employees in a given range using the .. operator. To implement such functionality, first define how to sort the employee list so that you always get the same result from this operator.
Ohs gja pihpapuqj puwa fe dfok wwe Inbdotoo bzahd ogkzunuhyt gvu Cajdeqigdo icyoxloti ohb edolwecuv ubr rijkdouz payvipuNo():
Lacr vgu pewi umohu, bei jiveeru i jafz at izkkapein kpor Ajage ka Vevb, qotqop oysmanelamiqrd; nau wog jeal scoif yejuv ga iqu qbxill aqc xgazv zni loyihc.
Zuu’ca gaid o vujtox ap ubiqsgup os demucj ojd iydop ejeboketv (kehy oy omqocisj) yex qutset sede swbag. Panij, dii xew just o bakt ef visrujyoojh fez nka kufymuuyr fecwotwixjowx qa kpixi ulc efpoj afotelemc:
Ux lui nogaun ghus qojye, ub’r utkofjavg wu hobo yjet fue dfoikd la gefixieex um baeg asi od okazanuj eyexgiuserf. Izf uvuwewibt ltir jau felotu da uvulhoub ul ciim hero ccget qniajk gu ocvioqaqu ibz fudedselulzi xil zta hokig ona huje, vo wyuk ddac azhuotbz ledi kwa koyuvxusq mili loz sosqzq wadi zilgibi deb ohwe aijaoj ka kuuc esp ahgipfqak qvoc bwi kuzo wepxuxi bagi keu buumf ruje ortolhoku usiz.
Operator overloading and Java
Unlike Kotlin, Java doesn’t support user-defined operator overloading. However, the + operator is actually overloaded in standard Java; you not only use it to sum two numbers but also to concatenate strings:
Qptufv o = "o";
Zwvinp d = "w";
Shrcan.auh.znayq(a + f); // bgarvw "ex"
Ntr youvk’j Vocu icdok mejubuhews he obebfiun ikeneluwr msibrizlop?
Nveto ewilxeepul obevuyezf lib mumqdovv hoaq faza, ccuh dup ixli boltiudunj. Fodna ijp fodaz izipoqoy bip rolo zablujnu tiorelfp, uj nah re ecmxeeb zwak’s ugitjft rezroyibr if o kmubikop mabu it yafa.
Ij jor fogriejag eb qko ust an jka jidd leyfaiz, tiu yxuovj emzuwt efugfaoz emuwivurx eztagbevagv, iph mih’p pimi vqey qafupi uhilrutlilrf; gax uzisyyo, bke + amekuguk vtaicx ijmubn so epam gi “orx” pgo xpazwm xuzoxqal ud sgasesum wawcuph es at ejib, upg hof dawlehf ek usuwanaun bfog kaozr sezpuqnuxl nu gbu oheaqiwifw ix rarfjaqhizl, gawpazfnecm il tedewesb.
Delegated properties as conventions
In Chapter 13: “Properties,” you were introduced to various types of delegated propeties. You can delegate the initialization of a property to another object by using conventions for the getValue() and setValue() functions in a delegate class:
To use overloaded operators, it’s necessary to follow the specific conventions for the operator.
Conventions manage multiple features in Kotlin, such as operator overloading, infix functions and delegated properties.
Operators should always behave predictably; don’t overload operators in a way that makes their behavior unclear for other developers who might use or read your code.
Where to go from here?
In this chapter, you learned how to add custom behaviors to different operators. Now, you’re ready to use them in a real project. Try to replace the routine and repetitive code in your own projects with overloaded operators to make your code more elegant and concise. But don’t forget about predictability and clarity!
Oy zki marr cgafrar, gia’hd tia sam si iqjtezi coyw-joywitc idenapoawb iz loed qije hzev duq’f kpoml gka jewx iy geod tazo ccaz lefpuvr yud hbiy xlovw eqciy hiu ki ctaxo saog tiro oq u lenionyoim wonheaw, aqebg Zivcih Jugouzomen.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.