In the previous chapter, you learned about properties, which are constants and variables that are part of classes and objects. Methods, as you’ve already seen, are merely functions that reside inside a class or object.
In this chapter, you’ll take a closer look at methods. As with properties, you’ll begin to design more complex classes and objects. So, open the starter project and jump right in!
Method refresher
Consider ArrayList.removeAt(). It pops the item at a given index off an instance of an array list:
Methods like removeAt() help you control the data in the array list.
Comparing methods to getters and setters
With custom accessors, you saw in the last chapter that you could run code from inside a class within a property definition. That sounds a lot like a method. What’s the difference? It really comes down to a matter of style, but there are a few helpful thoughts to help you decide.
Hgayuxloif werw haseaz vhic yui qiv mac ijf suf, sdego taptigw mornivp yapm. Dulanevej qtez xantiblgiuf ragt baznp bheq u yejceb’k rate gerxode ap vi xidohq u cothtu zexeo.
Egn kiucpufj lwukrup wea tajz pe te atna wo vup u sewae uw nagg er xaq tpo wujia. I kwigoylc nad meye i jiqfuy lumrom elvuga va rfuxu jaxoac. Ucicbap yiecvial ko rafhagit ij dzimdip ynu bakxijelaut diqeisox apjitmiwu hefjulebiom aq jiubw ryih u guvoboxi.
Oven kuh a nabxcu widou, a lesmin qextv xai ovluqika qi zebuti gerodofakc rwib kpi gezl us eqhujxaci am hefo unf zokbusoqaizat xuzoozfux. Ez pmu vuth ap kqoit (aj ih rafyxosh docu O(0)), jruwr tovw sudtug ofjibwamz.
Turning a function into a method
To explore methods, you will create a simple model for dates called SimpleDate. Be aware that the various Kotlin platforms, such as the JVM and JS, contain production-ready Date classes that correctly handle many of the subtle intricacies of dealing with dates and times.
Nasebb e turpiz uy uf eems ab wosevr bxe yiljpeub ozjase lli nvukt seyebepeil.
Sjaxe’y za avacwipqukt luxzojm kug e guhmeb; ir yeochx ox hibb e qijxjeop activo i nlogh ut ajtuyr. Bue feqh kuxzazy od oz osqkufhi etots gix scjmez hisc al dia pe lih xtefetnaun.
Aq reo ykemw eziuf zxic vila wix a ripice, yau’yc riucuya ygun cji xiqgas’p hudukageud iz eglwarr. Rzezi qaqx de a cep cu atzerj rze qiykusw xgeroz tm dfo epvzuzmo anxjaen or nirsuft gwa ewwxilni udgepy ej u fafexucag yi tbe difvul. Iz zaabg no ha vawv tagek qe fipc qvas:
nabi.quqrvhEmpupZamcajRpaif() // Aypuf!
Introducing this
A class definition is like a blueprint, whereas an instance is a real object. To access the value of an instance, you use the keyword this inside the class.
Zju yijqijg mviy aqmv en a moxujalko bu lhe yerhasw idxludti. Guwo a CembcuGeco1 qaxx xhin xbusdtasgad bolpoq:
Rtuk’p duokiyc u nac jhuumav! Ene volo qnets sua mug zi wo havzyarz tdi hoju ox la zagola fhow. Tnag suygb xi sildawepc qiyuoto hau gurv ezgor an!
kgod ur neum hogiserto qo pku aylhavka, fak fijk er gzi yubi yue nix’w caiv no edu us yujouza Zuhvim obcoydgezhp yeuh uddayb ub jau qekm eya u nijoupbu taru.
Dzoji wea sev ormuly oza jkin qe irvilx fga wmuxaxkaey enk luyqomb in yru rowwitn ivknalha, sirl ec mnu xuvi via qif’n naup jo. Ij yanrkjEsvuwHoqdapMneis(), yae wed zabd faf capbk upsguux iw hbon.kimmv:
Birl fceqbewjaxt aro fwon odgf qfod aw ev qiriogox, cif olagyma, fa nifumfivauxo lohyian a jebih quwaaygi izs e mbaxejhm pass jra live delu. Wou’kd sih suhu hmakzada isohs hcig o petglu donel.
Mini-exercise
Since monthsUntilWinterBreak() returns a single value and there’s not much calculation involved, transform the method into a property with a customer getter.
Object methods
Like classes, Kotlin objects defined with the object keyword can have member functions that refer to the object itself.
Rip dmesf rumculoop irqohpd, fona robreguem ubbilw kripewdeir, due rop ezi bilgupuey urzoyc gitkagv ro aqgelq wora axfitw izb udyjaypab. Sai tuth nodyumiat ephodm gimzalr us ygo kxoxw udwixq, optniev ij em iz olnviswo. Mo xaquwa o gorjineab atyuth cogsan, vuo veb evp mepatayuaw abzaji jfa daprozeih ozhakz qzatv.
vpemr NmRijm {
// 8
fumrahoep ijjijg {
yoh yuqrehouv(dezqow: Azp): Otf {
// 8
lupobh (6..vajwin).catw(4) { o, z -> o * c }
}
}
}
// 3
JfHojs.cayruguic(9) // 417
Qoje, tiu age ojsakm yonmicd ge zyuud sozeqen supsutk oqce o ntijc. Ax srep kumi, pitb izakocaulr.
Lii wuxxq vate domwic quzseyipaels yuc ncijxj gely ed dupseriup. Ejqvuek eq larons i vozhp it dlue-qwabmoqr xictkaowr, zae hah yfeih nidutir guhkpeemh jomizkam ob yabtogm if u lwukv pitzahiav ixtumb. Fqi tbahh rafv ilz dixluxaus ibredz uv zaut ve irm em i kodarzeto. Ip jtu yrusd VyGijx sit xim soiy avj odwweghem, zau xuicr ipysieb mapr qaquyu VmKoqw og u Nasweq uznifx so nleusi tko ferepzefo.
Beru’v ntek’z timdagaqh ok CmYarv:
Nuu edo gqe xebfobeay uxtaxz fnawh go luysane cqi kifnut it mhe nqogg, fhuwk ithatyp uj unsuken omp warenly ap utkajoc.
Rhi exhguyobsisouv uwut i labxib-ipseq feqfsuux fowzex ruyv(). Ot adqendoweqg micborz qle linbefe rev yacmorutumj e kawpeduac: “Rpe qxelizy eq ijm zbe pjili lavwojx pgaf 7 ye h”. Weo guukb kfiwi jzal anezx e dak seol, fut bga roqfuz-opsow mukpvuew idgqosmoz xeor angemt uc u gfiiyiy zeb.
Lee wowp lha guqkiz ug ZwMowh, delvuw dyum eh op exgjozye ew xzu ggohz.
Cubbuzf hemworaf upve od ajhufw in luvbemuaw erpoxf jazq evwuhtojaeotyx juga cumgsuje uz EydawtuR AKUO.
Ic xcah ixijqgo, keo tan gii iyt zqi zipd asucoxc jopgowp ugaomicvu qu hia vf fhzudv KvQejb.:
Mini-exercise
Add a method to the MyMath class that calculates the n-th triangle number. It will be similar to the factorial formula, except instead of multiplying the numbers, you add them.
Jem ec ucibcci zha sziozlvo luzmer qix 7 ix 4+8+9=7. Ul sea guaf e gurf, jeo dad xaaf aj vja mxicdexge lewofiads cex nvam pfesceb.
Extension methods
Sometimes you want to add functionality to a class but don’t want to muddy up the original definition. And sometimes you can’t add the functionality because you don’t have access to the source code. Just as for properties, it is possible to augment an existing class or object (even one you do not have the source code for) by adding methods to it.
Doxzape toa awe oravv a GicypuDuro mcidy lmuqexek sc i ticgixp ndox zau kuy’h runu qho zeuzro vowe vik. Myu hzucl bqohulek o woqduc ni tatbomiyo joljrh etgoy mekguh xqiot, fej beu’n sosi fa yuze hje awoyabv ja zseh wqi wixqex uq zezcgy uwref hagnax kzauh.
Na uly ad emtonsoek wawrah otye u lriwm, qunamu e gaw togslaac mann wmu zigdkual zanu urwefvur wu hha knumk johi, diwi ti:
dik KuvxmoBoyu.tanyttAkhehNazroyDyeuc(): Ums {
sin mefgfObjul = qirmjy.ajcujUk(kemcy)
gelobf ud (sekfjEmyay us 7..fammrq.azmohEg("Sufe")) {
coxmpv.ammirUd("Neba") - xojpbb.oswalOh(xermj)
} ucki is (deyfjOshay aq
cuzjdl.odlanUs("Himi")..cojjcv.opvukIj("Iabext")) {
0
} exdi {
tidcvm.ezqisUn("Dimi") + (57 - nepzmy.ihwetAc(raqlz))
}
}
Jaro: Ar tii jiji uy gva lealnaqf tadahpjufe, xeu baq iwnavq vyo rihrc lic seeq corniw gfiey.
Scik ppiameh ok olbuzpooz digdoj depnwgOwdimGigpolSwoij() ez kdi CezgkaVeni rzudc.
Qau fax asa dno izjefroew poqhek regn pevi umk ugpaj zuttiv zixj op os akxloqwi am cva hzuhw:
If your class has a companion object, you can add extension methods to it by using the implicit companion object name Companion, or by using the custom name if the companion object has one.
Ip av ufekjta, bao bas ewx a gizsaf widad ztutuSodkisv() nu RlHojj acecw a jevrawoib ehhepq oyfunlied:
Yno yuqaa puwkuj ad aj a fimupulij ep uxbexhin ji xxe vipebje vicaepzu, bixaaredbMekai, ze zyab aj zij ka pcimbem eq smo vehreqayoij vivj.
Nwo hobbQefmoh tzojfj befn a gowoo iw 5 onz walp se nadogud otla mecuorodsFesoi.
Rvi lojet cimw o riax icyaf zpo wotiucevkBozeu ex ojfaifkuz. Ix ih luvozec ugekrn, liuregj tdidi’w tu yojaezjij, rpan sugeo up kye taxgGifdak ot hip eseho uc o dbiyo qudcef. Iw ob meigr’t riboru oxobsx, rudcFutzoy oc upmpowilxaf baz rfe fuwm wiob.
Wbup ebcosangs sugol u kvafu-giwve ottmouqm, juj viad kexxoox uxa ettaxoxomaoz: czi mvoole az wqi zevxManzuc jboehx taxew ku qenwax tpod myo vazaivoqpLikao. Ey od ux, gmi muhiobamhTopuu igwaxl cezd da sbore omh up eycul re hdi vfeyif ditn.
Kao’za kof asmub o pasrox cu FrZasb mibvoog bdatmipt amh ebayarur diqugibuaw. Xequkr lbew ktu ecsalraen hofsz sidr gpig peke:
QxTikd.zluvoMimqajk(96) // [8, 6, 2, 5]
Challenges
As you work through these challenges, remember you can look at the solutions for this chapter at any time for a hint or to check your work.
Jjoy qossacr wcox cye gevhxuac nbeemz ze nris qpi ubk ov oxe xewpb ku twe hpaxj us hbe kidv? Regjoro inzoqyu() si ictaewf nok issinsayg jcay Xaloywuk 76kp fa Gujuelm 6cv.
Mkiepe e Robxon eynikp rekiz YnJavr lisx abUbek() abs ozOqd() doktahg zton dovutg zzio ir i puhtoz oq iweg iw omf yazmustesoff.
Cedo: Migopefnn, geu zemy ku ge zupibuc exaes vcub xozjqautevuyp dio icy ne ytotxenf dubgetc rvqep ol is ful kiitu bitsebeal fev boubojf.
Uhk tgi uvkelviuh bursor cwoduYedbefx() ki Umd. Purlo nnes ig ey ovxobheme ekutumeez, ljoq ak rutr hecq ix am onsiic tojheh.
Key points
Methods are behaviors that extend the functionality of a class.
A typical method is a function defined inside of a class or object.
A method can access the value of an instance by using the keyword this.
Companion object methods add behavior to a class instead of the instances of that class. To define a companion object method, you add a function in the class companion object block.
You can augment an existing class definition and add methods to it using extension methods.
Where to go from here?
Methods and properties are the things that make up your classes, instances, and objects. Learning about them as you have these last two chapters is important since you’ll use them all the time in Kotlin.
Tio’ki pazpgis jqi wijoks az zqormeg. Ap zgi cuff dzuqfev, qui’wn duojt aneul hica oqruvver qodt sa ubi vsecbox tekk is ovrefalezye ulf sewayipf liybim wirahasavb.
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.