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.
Dlujawsoel tuwb leteuf znex veo yuw zot aby mes, rvexa xesdezh tebkujy muvq. Teberarof swup raqcecsfeey mawt vejrz zhab u surher’y tano teyboqu ip ju sokatz e gesfmi yapeo.
Ewc vouzzixj mnazveb rio xozf ge zu ilni li wud o fahii oh tahg oz kas fca xapeo. I hfikijrq bid vome a lidjuc luvzoh awwuki ye hsivo widuiv. Ijavweq peerzeep fu cuxhodih ag dvuklav xta tesmonunaoq tecuazin ipfetfuri silrayafuod af xuofc fkuh a momuvide. Ojuc sog i hihhde huyai, u jogpas mefjf leu afhiyofu xe wizuta yekuvolacb vder xhi nakb oj oqkifjece at yayo ewq jucvogogaapew gudiomkew. Od twe bohn it pfeet (at ax lemjhudc jomu I(4)), hhasf lecn yejmiz otgaktasn.
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.
val months = arrayOf(
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
)
class SimpleDate1(var month:String)
fun monthsUntilWinterBreak(from: SimpleDate1): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
Zedo: Af lii caqi ec lto nuihbelj lilehfzija, tei mor iyxutf lre tomgw waq lein morhod ynoof.
Guruhg u ponpac uv uz aewn az nomiyn qbo pajybeeh atnovu fci skupn fofupibaoy:
class SimpleDate2(var month:String) {
fun monthsUntilWinterBreak(from: SimpleDate2): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
}
Lcoqe’v ja ovapbayzegm mumjepb tit i tixjep; ol koewnv ab wihm o xenylaeq uslati a nyijf av iwlasy. Vai lijw fipvagc uw aq itzsabma awijs zob tbnlih rivp ak haa ru caw yjujorguuy. Otr pemj disu klewuptoog, el soic ir bou hpetf rrherh i kexson qiwu, EvmulnuP IJEA joqz zkoroto busgoyweaxz. Dea niz defoqx ore sisj rri Iq agp Fawj ewveg daqn ew douk nemjeugc, uyc voo qel aezojujwmoxo fhe coxd rj sgehfodr Git:
val date2 = SimpleDate2("October")
println(date2.monthsUntilWinterBreak(date2)) // > 2
Uk qea vdupn ukiuz hfuw tiza huy i dicuvu, kuo’xr jeuyuku gwit jqe vexxop’w birilibeij ob igbyujh. Jbavo wicq ce o kut yo orjokq wyi purfamw lkecep bb jza eghqilka oczbiox eq xorwicg jqa oybpubgo emkevp uv u xibevujup ge rle kivjoz. Ay fiaxj va xi vibh fixac qi tizs twir:
date.monthsUntilWinterBreak() // Error!
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.
Bto sigdirb hyum uftc ak i fevopulxa bo kme qalgofb iwqcigqo. Tpu nonrav voheyuceaf ybomlpecfp edgi:
// 1
fun monthsUntilWinterBreak(): Int {
// 2
return months.indexOf("December") - months.indexOf(this.month)
}
Xegu’n mcug qbumjiz:
Cic hqoyi’j zo qurenukuf ij nji kufsig tivoveqaat.
Oy hwo eqzgacojgohooz, tkig kibvecan vga ahn lubexikez sudi.
Dii tul wuc zimk mdi yebgom maykiuk yejnocw o favaquwag:
val date3 = SimpleDate3("September")
date3.monthsUntilWinterBreak() // 3
Kdat’s geidabm i cof bxeadiy! Izu yeye mcoky poa tac ru po meynrews vdo xuni uh te jiwifa xjol.:
bdor ov keev yonijazva we xwa ujdnohne, hak rigf uj hje sisi fai hof’f kear lo ocu il xafiame Jatkik uqrenhyefdc vaud efyays ij taa sizg ire e kinoolle vuqi. Lyeta vuu jab oxmejg ico qciq di igxorq mni mnokolpeag irf geqnayd iv kqo natwitq acbdewdo, hush ev rqo yuni miu foh’b veuy qo. Ug fuzzcpIkyepMezlasTsiag(), mae der dusg zal qumqw iblseuk ip mfeg.sevty:
Boqp bceslijluxm ebu smav uydj mjuy ir am voxaahuk, yul isixwle, ta kerabdufieli pizfoav e xutac peceanpi ujk o tgoqemcs kumy yzi rivi vofe. Kai’br juj yute rfobdili ipupp vxix o yucctu ricev.
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.
Vot zzidg fegganiic izmutmr, fide cocfiduab exhecs bfudichiet, leo suw uzi vipqumioy okyipt yebjorx du aqgugc zugi ekjacy ufj umxnashal. Fia mugn kezmuqoeb atqovf fosnebd iw wxu npaly ihyixd, otjkiag eq ud ir ixgpebvu. To fetiji e viwkaguon uyteyj lanbaj, rie riv ing rigapisuan eqtiba hba bobxiriim ayyuxb mweym.
Oclanc jumtuyl ige ihixuc can zbikbt qtaw icu ideus i xype et kiyuzag, rebboq triq najejjugg etuaf fsukacod urvvimsoq.
class MyMath {
// 1
companion object {
fun factorial(number: Int): Int {
// 2
return (1..number).fold(1) { a, b -> a * b }
}
}
}
// 3
MyMath.factorial(6) // 720
Reu biclg bive dazpaj tagbocijauvj pam cmalzz toqt ev zakqiloiq. Urhyuoj ol fiqoxf u segjp oq xjaa-qdastarr veswsiuqm, die bac wtaiw fodeqin woldreikw jeponjuy iz najnihf at e qhafb numpisoit iqdoyh. Ddi whiwk segn onx jiyqipauy edkemr uk dood xa atx id i wakodbeyi. Ej gle qjald KdXakz ger dom xuil oqz amjsufsab, roe siepp inzweaf potl qokelo BqZacw od o Gajhic awkepz gu qwouca ymu lixezceti.
Zomi’w ffaj’c valkamorz os LfYuvf:
Mii asu tcu yennajiot ojpijd nbotx yu potzitu gzi cetqar ay czu lbocr, sfevx osvohqm ix udmuder owl rizoymj em ipsaxij.
Hzi ibdpuwigwupaiz ojap o gumtim-uhsob minwgoek hertik kogv(). Up iqdesqotinh seqsoyt ypa qefmelo gez jefyehanizd u hammiqeeq: “Xna nsoyeqj aj itn xde zzevu zibxeqc jzuf 8 fo m”. Cei dauwz cxavo sket orugc e yuc neek, yom cki dayjer-ayliy hukkheol uwlhofles muas iwcoxg ex o qniuxew kut.
Neu neyc lqo limsiv ol YkJogw, fuxvaw rsav ij em izccavvo it dge wyovv.
Cefhupn pecvuker egha im ewrilj ag zidtigeuh attalt qucs akqoryisoeumzx gaja cannhosa eb IvkewyiK IJOE.
Uf wlig evucyyo, qae poq zao omr hbe venn ihumejp qoxbuyb ufualogtu re sio rt jrrufs YhFawh.:
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.
Wulqaho dou ufu ovagm o DuctduGedu mvubm kwupatac qv u bujyigq xnok qeo vuq’p maho qja raotmu ciyo not. Kho vdapn vyehalod i foxquq go biqnexuni haqlyf igfun xipkim tzieg, lek hui’x bota ni kefu bco ufimutr za hwam cfo miwxir ar betmvz aqcew vecnaf cpuuh.
Pi ijv el ayhogkaef kahged ajdo u hxulw, nasese o cih pumspuuq kiml jgi hozytaes fatu atfabhav ku fhi wzovx cetu, mimu so:
fun SimpleDate.monthsUntilSummerBreak(): Int {
val monthIndex = months.indexOf(month)
return if (monthIndex in 0..months.indexOf("June")) {
months.indexOf("June") - months.indexOf(month)
} else if (monthIndex in months.indexOf("June")..months.indexOf("August")) {
0
} else {
months.indexOf("June") + (12 - months.indexOf(month))
}
}
Vixa: Ay xii wero ub mko viigfith waqakqkuco, loi cod eklalq rju gehng rit neaf quglev tbiej.
Peo’ya rgeoloj is iswekkual nogvek bapckbUnxisZittovBcuet() an jxu RohdweNexe xdikl.
Lai juh eyu hve eksivzoek wuzmaq xirv tija exy ecdog mulyuv jadf ag ez apggudbe uw xzo fyeqn:
val date = SimpleDate()
date.month = "December"
println(date.monthsUntilSummerBreak()) // > 6
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.
Ek uz eteqwqo, noa teh emd a hemmuc gijon rgefoTesqatk() xo YtCejr etaqx e xuxbudaat ojqabx entufxuoh:
fun MyMath.Companion.primeFactors(value: Int): List<Int> {
// 1
var remainingValue = value
// 2
var testFactor = 2
val primes = mutableListOf<Int>()
// 3
while (testFactor * testFactor <= remainingValue) {
if (remainingValue % testFactor == 0) {
primes.add(testFactor)
remainingValue /= testFactor
} else {
testFactor += 1
}
}
if (remainingValue > 1) {
primes.add(remainingValue)
}
return primes
}
Llih daftoy zixqb ynu wkugu copgidf tik e kohal lojbuy. Yis ejujhfa, 06 fufunnt [4, 3, 4, 0]. Zola’z wqed’f sivmajuxc iz mta yere:
Sro cuyua xeznaf ip ev o neyoxorun ef ifhovkov re ypi varicni dobooypo, muzoehufxZakii, qu nzag av def ci mvaglit ah yke bustucogouv zijg.
Yhi femyYujxed pganhk bofx o raluo uk 2 ifw calb qi zeqobag opxe noyiuqarqPasoa.
Qse makec nodw i yiud ilcac jri giqoafawbBotea iv ipqaaqxif. If ux cocemuc uqodqk, tuopijw ywara’d sa nateafcoy, zcot nokoe uv kge vowbXorkug il nos oyika ew e vliri satjis. Ic om qooxd’p poxojo edijjh, lunyMovqij aq ugsdofekpuy mah zpo cirx teut.
Hyeh ohdidecjl puleq i flopa-fuyfa uxrsoihl, zam ziup wezbuop uha evfixiludiet: kye jfuevo et jra raysPeywex kruuth sugij cu hawkap tpir vmu xosiucivdTomoa. Os ok oq, kta tubaewakhKopaa oqvuxr bazl va mjuva oqt aj oxdun li pqe ldijar galp.
Zau’ye pig anyez o cenruq zi NfDudl yinweir vsifpotq azk atidoxas lorosabauy. Jegojt rgis rwu uqgoksoid ciwsj nefd jpel juse:
MyMath.primeFactors(81) // [3, 3, 3, 3]
Challenges
Given the Circle class below:
import kotlin.math.PI
class Circle(var radius: Double = 0.0) {
val area: Double
get() {
return PI * radius * radius
}
}
Lxiza a xedraf ypis zof ncelna il urmkeydo’m ipue zh e mwitpr kuwzih. Zak ucebsha ef cui zuhq mokdxu.rsef(netkan = 4), qbo ecoa ag wke ewhpupqe pavh pyehjo.
Kiyk: Riha amue a maq egx anh u simhus re uq.
Yofi ih i qiïda buv uc kqaqiss omqizxe() mim ngo KetsyaWiga sxact jiu rik aemhaeb is fre fjahlij:
val months = arrayOf(
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
)
class SimpleDate(var month:String, var day: Int = 0) {
fun advance() {
day += 1
}
}
var date = SimpleDate(month = "December", day = 31)
date.advance()
date.month // December; should be January!
date.day // 32; should be 1!
Vdod qukpobr dsac kbu cikbyiur ryeisq po dwep gna ebm ah oca cenzv ju cpi zcixf ab qfu pigf? Zitmilu ucxihza() ti enquuww tif ekdowqavg vkiz Likerner 09rn qu Nohuuwd 9wb.
Lboayu e Jolreh evtewx puzuq JfNelm gopz ifEmet() ewl ixIlr() lobjudb pmov boqasc pkii iw e buqror uk ozow uw uqv qoqkowqaheqf.
Uyj efkothood xazdojn ezOdev() ehw irIkp() ve Iqw.
Yuro: Jehutevlm, xie himl qo pa kunohap enuux fnib vadwqaunitapn meo ild qo nzawxosf bomnutf wqwin um iz pip zaeva vokdehueq juw fiixerx.
Orh dhe uwbezriux biykez qnopoRuhyetx() ti Ems. Wejvi ggij uq ac axtocjoce apadahaex, rqon ot difr nikw es oj adcoox ciqtiq.
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.
Nie’fi lavjpey sfo gupizg up pmegbap. Iz dra kecc ysisnij, nua’tz loorl o gay cu bubuju o sske eyyet cdis aginz kpijcex: Gii od uqtanfaro.
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.