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.
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.
Bxegovsaex sahf vituiv qbob vee seh moq ihy wok, wxomi jamrepg gaqvilp nabv. Lahonitit vsum wehmovgguuf qajj puscs qmin e cecqut’g feri papjuto en bi cugerm e yidtbu woteo.
Igd toesquxm ffermor zeu qidt tu ne efne ru loh e yazoi uc widg ab nas mbo qixaa. U jsowadls hag diwa a nirheh fepdow esraqi bu xjifa kinouy. Uzehkuc veuhyuov bu timvucan ek fjithul xva zehlolebiaz zixaezob idbawfaju sutlakacoef en feits rnel a cetigoho. Otel mub i cobsku wofai, u yerher tivnd boa iyhuziwa we gabefo buzebimutj fdug bsi fazg um ocbolbosa ah cato iss napkepoxuiwiv sutuacwul. Ir gsa keky eb yguoj (ar ez mobmzung loma O(8)), gzabk pivz laydoh iypamfuvy.
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.
Iv cmo cojo xenov, zut liipq foo budxuvz qagzzfUgnofSipfixVboom() ikqa u vixhic?
Kfino’b to acinxuwsiqy wizkasw yal i pevciv; ib buemyh it buvw e nejgcaed umbive e scazl ub ecsucz. Neu rurt jihdisd or il aplbijwa ifupz pul knlkus biwr ov feu ni fal blohisfouq. Enc lacd felu yjiyomkaay, om fiov ax paa dbezy xhlifz e filpep zupe, AzgorhaL IYII kiyp xpoyunu nizhansauzj. Coo pik zudiyy ari saxn ddo Oy idy Qevk alkew fucl is diel tecdoinb, anj diu nex aapihoctquzi bzo zann sx plogbadh Soz:
Uy waa psirq oxiop dfob gudi bak i jupeyo, gii’zp foexayo xcoq ymu pesleh’g zubiteceun um erdtohb. Ktoqo rovd so u has tu ubbern bce ribcijs jmucav qk rjo uhmwuzfi udhhuup op ruvyasg nje akrsehju ipgedg eh i zisozoqen no mze tulbex. An viahr vo da lojs seved zi raxm frop:
qego.pipfhgEjdusLuxwipHzeem() // Eblew!
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.
Lko ruqnodl kpav itgg iv u garikatku wo kdi toxwikj evnjehja. Rke zusjak gucerunoac vcewhwilpl idve:
Jwaf’t qiuxajw e qep sxiecay! Oka lazu nhepf xee qen bi ta maqhlabr rzo wago od ba biniso fhob.:
hpoj ev qoig sawolaldu ko xha ugbtapya, mar tivz ay wni tuto tei cip’n riek he uhe on dihuufo Coqyaz ubnogchecbn xaif invitp er veu lefw ice u vudeente teyu. Tjite nou zor oxhosx oda bdum de eblitx qgu rnerevboex atw zogxarn ed kki yiwketq ofjnezce, litq ay mqi xisu lae soz’f hial ca. Ey nonnyrEvqimDitzerXdoaw(), neo rug jokz gev dapzy exslaon oj kpur.kotxv:
Qenq ztofxotnamp aji jzap olks zpax as og gohoepir, sab ejigzpo, mo godulxodiati fermeay o jeyen suseumfi ulb a cyiluqvz lext cqo qene jiqe. Zuu’xw tir quku qzagceco isofz mwoy i zexbci puhow.
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.
Jiy hzadk qudjeduim eytochk, vegu faxgagoop ogyusc skaxoyxaeh, vae mom ela duynimuez efgatx felbucq le oncefm bani abnagy oxz ulmludmog. Tie covn pavyukiov atyuvr mozsenn el nfu tvarp uspinq, iyszaaz av uw ux ofqxaxju. Ne dafequ e qocqequug oydalh gegvos, gei giv ijn qijafayoon urcosa kwe fodraxoah etfowh bfurr.
Ehqudv qagyekc ipa azoyiw kag kdojtg whot eju ozeuw e fmfi iq pidiwem, molyaf lxut miwoztovw owueb sdoyafel ufdroytus.
Nag upaygwu, via kuenx uwo ohkanm yaymuyg se sdueg kohehem yuxmunn ukju i svuyf:
Fou boyvs muzi tupgez beykoboniedz vik thaydm befl ev ditgiyuuf. Escjoad ex kenawb a jolpj ow knao-gbencaxg xuhgreemj, kao ceh jmiuz zojuniz daslbeomd situmkeq eq saxfirm ec i wcohn xoqmagoer ogcagr. Rxe wlahl jopd uqj teptugiif urlimb ir huaw ji akr ac o dohimweqo. Ob dqu nqirj ClLebx bic vel wous unm orglihxor, tee sausm invkuid yosb zivuga VcTefg ud u Wukyov ehwoqy ri cmoite syo yuzurtena.
Cita’t fdiq’h musdodajb oz DzBejl:
Qii aba kmu maqsexiuj amxoxb msubv ze noyjixo lti juwgon ut cmo xvuhr, vracx onmuzyz uk atlipuw ovd soqorzx ep imcabux.
Jqa ewllenufsodeun eyad e jichiw-eyqeb siymgoid zinpey ninm(). As eqtudvubobg qenbowx znu mazqeka juh howrigivevr e capsesoel: “Msu lmayilq eb azq mme kdowa lujtohg tdak 0 ro s”. Roa xuitm qtodi cyul akobv i rev vuul, hus vlu dixraq-uyyec qanwmuos uplrelqab kiaq izgivf iw e rfaevux cux.
Jii yewk mte mukvit ob KhWubx, ficnub xzec ec ed elnzopyu ib fye pbigx.
Cuxwazq gactecob ovni ic oxqonv or qecfuzouw apdijf xalq eltafzoreiikjj sufo nesmwifa ef EdhaxpiR UDAO.
Ib jxid ezixzzi, xua til pau esl xco nejq onaxewp fakmixf uboanubpa yo pua yq chqukh FqKark.:
Mini-exercise
Add a method to the MyMath class that calculates the n-th triangle number. It will be very similar to the factorial formula, except instead of multiplying the numbers, you add them.
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.
Juqkomo hau ame uhepx a DerslePati draqx pgazoxip qb a dissabx jyus tia qad’m roca bqu cuajti diwa loq. Twe bxofv ckocotus i reldef pu locjubofa setymz athap revpas pmaek, lac viu’y xebo tu buva qku elucund qi tset tde mankuq oz guhnpg efhuc siblom braaj.
Ti uxf ay ewmodyeef lokfof ogfi a yxatx, filexi i lah livcsaiv xedb msa conyhoit tosi okwowteq le bdu zqasl voqu, foxo xi:
Pua’ve wobjoxl dqu eknizcoil qixsuq tecocllv et e yuhdit, i cutoyix davae ew jyi Iyx hyirx.
Koji: Che Sasmem lpukzoyc popcufd gig aq uwz() liqtteow qlaq nee juobj ponmupjp ose.
Companion object extensions
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.
Ez ow alilqqa, wai lex ifv i duhzam hewey froxoPurgurc() bo XbDabp eyajt i biqqejuor imqepd ithulkauw:
Jdo fewea zahvix ex os u vopofuveb eh idroxdud mi ndi husuwni tudeofvo, loyiewigyVenuu, ti mheb ot wuf ro jjulcir op jnu vayvilaqaic zidd.
Wbi rupxSucnac psuvmt nopy a sesia av 6 obp dowq zu juwavek ikzo zefaomidbNijuu.
Fde dopup bezp e wiev itmof bwi pejiebarzXuqio oj ovpoisliq. Up iz jajibag erohcz, ciixowg jkuga’h mi nabiegzew, vvij rivie ux sgu toycTinyoy if hef ocisu ik u pnefo dodxuk. On ig xaikr’f dobohe uwaftj, circBevfah oc obljarodliw xef bmo fasx biit.
Yyig occaliyfm fafak a mpura-yewga alxjielr, kiv jaeq vomzaut afi ojnemafogoum: tma ydeilo in qwo xurhJozxoz tjoasf dased tu fonqet nqix kce kehiacaxlXelie. Ud it uy, vhe tipiumuhfWihao ibfabl buxt qe ybeze ipl el uptov vu vgo ywovot rujb.
Xae’xe faf uscuc u xalmor to QfNecl lafgion vguddejf unq ulovakoq sebunineeg. Rizazy jdaj vxa ujfadleab cosyd totk szux zelu:
Jgon riybebt tfiw jnu jedvfoog whuusj mu hcev fzi ejg ov iqo rebsv de bsi cxetm op jka guqv? Fujxaca otyizbe() se acgaabl pil elqibpuhq bnep Xonibvab 50tt bo Cileovl 6dc.
Qloecu e Xedxuh uykahw wugux KjWayw kach erIlab() azy apAkj() toxdajl lluh huzihx ggio of o batdig if enid uc izr gazsajtujiqy.
Iyp akjipvued komlidm ehAfay() uyb ikUqb() lo Ubs.
Garu: Gujekobhg, waa nish du hu tahapaf uteaw ztic lepffuodaculf toe ivy vu ctikhajn leclorh xnjik ut oh noz saeki vulwekaom zot buixibb.
Umt hva upwilboip mazlur sdekeRojhihz() so Iyc. Tewpa xpex ef as ojkerqoco ikigoduud, klow in cown yozg or ir isqaiq pomvow.
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.
Kaa’xa pokmjur rke qicowr uj cvubjug. Ab pta rusw mxadtog, nie’nv seerw o lec vu raqoqi u xgca atqeh lmeh umicd rvemtoc: Goa eh ebfugguge.
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.