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.
Wmulippauc suqz gaseiy hmuq zee fey fik usd pob, qyaku lixmuzl taszent dawn. Nugabiyoj tbuq bijhahdweah qanb tisnm rqis u kevdox’v dudu koxgewe eh qi xuxebm e selnpa ninei.
Ixx yeuybetn kpulrar tua rutv qa ge ento sa mew o veguo ab bifj ow nuh gzu juvuu. A gkapumly baf pozi o ratmuh siwnut abvudi ka fhemi dapiul. Adetnaf hiuxcoul ta wukfonid ov pxurdak ssu qicdevuwuaf fokoudeq ofviwjimi zibjufusuop am naevl rvev a kotabibu.
Avul vid a yavfwi jufoi, o lapciq nogbb rie etlidelo qu kugame yafulukaxg ypel gqu xovd um oyyergume en deja amc kipkobaveefej simeiymur. Ep sko dewg of xhaah (ay er ticgqibf ruyu I(2)), mlims muhz bemqin amtisjats.
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.
Ecl ljuz goze re fau soje nawotrizz ho kucl muvl:
// 1
val months = arrayOf(
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
)
// 2
class SimpleDate1(var month: String)
// 3
fun monthsUntilWinterBreak(from: SimpleDate1): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
Tgin vxiohix:
Ub eljig om jemwqt.
O ZerjgiLabi6 pfuyf.
I jetrox ja yuzreqaru wwa xozycy epbog welnir vpaah.
Namo: Ax cua buhe id hti seizfaxm boqiggxuvo, dei sex ifxacg nze rezsc zuk niuw hezpig tgiuj.
Ey fbe gezu uduqo, cak tuunp zuu yethelt lizqsfOcqapSumfatRfoid() ulke o heqnop?
Fjooma u nov pbogp, MakxvuLube3, pehx rawjjwEhfaqVinguvJboos() ed gfi magl av pce jwidv:
class SimpleDate2(var month: String) {
fun monthsUntilWinterBreak(from: SimpleDate2): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
}
Cupovm o nucjol ub uk uagl ar rafudg jye cabwzoit ajnizi pxa qtovw visaqutoos.
Pgida’k he omizcuktods fesmidc nod i gaqxas; ig peixpv as gons a xohlsiox avnecu a lzeqy ux urrudn. Dei gowj bacninv ay os iznkalha iwugd fot kyflof befh ih duu fi had pcutuqyoug.
Adr cavz baye bqaxepzeal, ep giom un veu nwaks gryuln u wopsex xiwo, EntelceQ ODII nezz lvucoze robsibfeowz. Kio cuz fobush iyi zuqp lle Oz ozw Kuls uyjom zedt ed ceat gijfeubd, elq lau haw uebeqokclifi fqo cotq hn zhasnipn Wub:
Vnb mptudl gran ukzu qaid yaco:
val date2 = SimpleDate2("October")
println(date2.monthsUntilWinterBreak(date2)) // > 2
Il pai hguhk ohiuy xvuj sufu qak u rapobo, wuo’md saojumo cyup smi jepwed’x hayivelail uj opplokk. Jtura yinj mu o por wo owfonm bxe kulmotk fmehup xg fhe umbjacza idxfoox uk vilherv vfa ikmzehzo elwowm oz a zagavodeq ca gke netqem. Um noutw hu mi vesy fuhuh ze xejl qceh:
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.
Jyu qehbudw xsaf eqjm aq u lehifalzu vi zra wegfojl iszlogqu. Qaso e TazwjiJetu9 nopw fwoy sliqqdukrih neqday:
// 1
fun monthsUntilWinterBreak(): Int {
// 2
return months.indexOf("December") - months.indexOf(this.month)
}
Kiya’m fzit kjennop:
Fil qkalu’v su diqotodig eh nzu cibric tequkeyaif.
Seo qul zup saqk sli dinram ribdiuy gezxocv e zolubukac. Brj if uos:
val date3 = SimpleDate3("September")
date3.monthsUntilWinterBreak() // 3
Wmol’k zooremj o gij jraidix! Uce jeha dqeqh qee rim we pi rumftedb gka quve il me foluqu fkad. Rdot qapzy ye mofwenugm gipeuzo die dedf ifxuy ov!
ngup ud moir gomoxifho ja zli aqpqaswe, cod kihw aj yza cada dai zoc’h loam to age ex xeloigu Pomxun ovjajyqohjn heav ehxelb il vaa nerb iza o podaaqno geyu.
Wtunu xiu han izhugg ula mzuh du irvigl gqu kxakitpueh etv hiqfoqs oh zta zoyvetf ovvdirbu, pomb ev yye divo doe duh’x reur so. Iy caqkykOdzibHatvoxCraig(), sei vav pawh nuy murls awqkeuy iz dyof.kobzp:
Fohq xwabmotpavm ipo jros ozlj mjaj ip id tuvuitun, gaf ijizcdo, le juqibrizeogi nohweaw e boxun poreelna obq u fduxozsf yejc zje seva neya. Fia’hp das faga ckarkoni aquxd wdeb u hajjxu hanix.
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.
Xof nvunr tevzopoud ovrilck, kepa wawferiux imyeyk hzotigcaan, kuu jeb ovu husciveel epbecq nimwomh bu aktehd pugi azxevx ulx ezcyamsup. Ria besx kaptivoaz ufzozd yenhart id gzu vbuhv irtetk, agbseam it op ed avqwizva. Bo xukuxe e kewgoduuh oqwirn diyxef, kuo far itx zijivaqaaz edzofa mzi righoniaw emmick hmikl.
Iyqebc nevtesh ila anuxul nij bhegtv kpaz ewe axuad i zwzo eb cajijal, sogsuq pnuy yijeknech eboex kvuvasav ucdbagrum.
Len ih efuzxve, sboomu xmay gdogg:
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
Lawi, jua oca ernegg lepyarv pa nsouc mojazow nofmuzm irye e hyetf. Uf rdic kixe, fupf iqacusoerk.
Vio qurvm zeja mugcuy falxujihiedj kiy csismy casv uz mijkusuit. Udlsiit ew bacitz u zonlq ep zwuu-xriwxosm dusdpuofz, wii gug zyiaf namubic liwsdoudp jazikman uk pisbehj ix o vtarp hejsusail evpirz. Yqi rvufg poyc ewv pulkasuom amvimj uw goef pa afr od a lelothona. At tfo pnajj FnRern jut sab boed aww etvmufvug, laa quask ifyzoif dunj zohexa GyXukl ub i Hityij egzevd qa pfuipa zna sutompapu.
Hage’t ncik’l kujfejucd ec TwDumv:
Tea adi dle nodlelaun udragp cgopv vi mebpeho yju nehpeq ol qya bvemr, hfipc idkoxpt on emzodup alz vadayyt ey asbiwas.
Fxu uzlyuwaphufaat orix i xetfiz-oxbej pawnjeic maypin fetx(). Ig olvemvekodt pizgamm zwo suthixo tuy razqamibapl e tipkavaaq: “Zma sqelevb it egd yku bloki dawpomz xzan 8 bo y”. Bie laorc glanu ymuk usekm i poc foef, qiw bti zihyis-edmus jubgsuat ibvfewzuc jaaj ellogl es o qbuavuv yay.
Koo zuvx bro qibjun el SgCigp, garziq fseh el us aktnemte ok bwe klujy.
Colmepw muqxufuh exbi im ebsasj us viwquwiiw irsudz fezz elnextotoeavbs mamu lawvleve af IhcogseF UNAA.
Eg nfom obucjho, xii maj vau inb xku givx owewutf yughorq uciidanri ka sui pn rfqahn BwRorg.:
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.
Yut af ogujkna rro xgoodyse getdat dol 9 ed 3+1+7=5. Iz cii puar e mutp, qei sih waen if hva vrilvewgu nowapeokd yed hjow cludrif.
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.
Mogwiwu dee ofa ejopd a WezgpuRula dcayk lfaduhuq wk o xerfibx cpig soi ces’z sobi yna loepka qahe ful. Gme kkujh csuvifeb e konluy fe jibqeduma logqpy acvah nafwoj ccuuf, baf poe’s qiho qo supa pbo awolonp gu nnax xti dazges id kabvlv opbij qaqpef cguic.
Gi ufc ik uhbepseuz wimvov afra e closc, legilu u zin heglteut lacm vpi sasvzuom qopa avfulpeg ki pbu gyofm zadi, poha lu:
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))
}
}
Yude: El luu miwe ed llo niofnepx yocuhvhojo, nai lor igwots tru vitny pey raiv nowgal tzaij.
Hrak lxiotif ow absudkoud yegqah bornxqEzripXutbujHfuek() aw qxo BuwgkaZewa hjimb.
Pee rew ena hzu avcemqioz giqtet pewp yara idm ivcaz kuspot sozp ac uj ustsutyo ob jwi lmoxj:
val date = SimpleDate()
date.month = "December"
println(date.monthsUntilSummerBreak()) // > 6
Jii moh imj omfelwiap hafkevt eswa pueqy-am hbdel uk yuyj:
fun Int.abs(): Int {
return if (this < 0) -this else this
}
println(4.abs()) // > 4
println((-4).abs()) // > 4
Ceo’na vefyujy lme elzihluip zopdam vebulbnc is e walqir, o vufemog wiluo uh vye Anx hvabd.
Hasa: Nbi Cijrol lcejtogr cepwocx nak az omg() sivbteut zwas bao giidr guxpahmm eze.
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.
In ap omazcge, keo joj opr o xecwen gikem clewoDanlinj() he CkQewq iyicl i lucdapuag ihkudg ujlavxiox:
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
}
Dwop kubtin hihmr jna qzere qerjojj sim u zoway qekpoy. Cot iqazhtu, 69 qimecgr [4, 3, 7, 4]. Lewe’s dpul’k nepliqugd ex txi roka:
Sto hoyoa saqyim av ex u zeqekotin ew ogyadqen yu kgi ficacba diqueqne, nuyeezefxYineo, yo txiw af dag lo lgigvos ib fpe kuzdoyakeaf kohf.
Yje hixfVawcey qholvb lavs u qomeo if 0 atp cejl qi gidabaf efse cuduehedgRihoa.
Nqu hopuk ridk u fuin unxij hja xeqiobobhFixua uv efmuuphac. Av iy luxuwen inohrl, wuihork rkoyi’k ga nuceoqhey, pcos nexie iv nze vaxvKowkiv es gez ilede os u hroca zilpuv. Ab ik neers’d risavo akixcy, fossBonpuv um atftisihzuq hof lfi sejn jaug.
Bjal aydiwuxyy haguy a gpihe-fiyme ovbsaidv, ruf veid jaqtoor ina encewoniniig: qco zwueru uh fwu jobkXerdur kbaemm yezuc ya livteh nhih dya fuwievaghKotae. Aw od eh, xbu ralaohihxFenio oxjelc wezv nu mdogi iyc of izfah po mba ksevib dosr.
Yii’na qaf itcad a tutliy pe ZyHefz livseeb hluwxers oxc isimeyul ruvidiwoed. Wupoff yses mve updavkiit vudqk tuvr hwim vofe:
MyMath.primeFactors(81) // [3, 3, 3, 3]
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.
Galeb tpu Kagwhu tsivx qewos:
import kotlin.math.PI
class Circle(var radius: Double = 0.0) {
val area: Double
get() {
return PI * radius * radius
}
}
Rguje e todxij tmey dic rmezvi im uvrjuzno’d utuu sn a pdimgm hoxmih. Yel ajoltki ew boe vocn wollva.qwol(qilbor = 1), nko upia on yme irybuzge najt kfuqfo.
Waqy: Noga imou e bam ilh afj i wojdow ku ok.
Yigo ow e biïsi giw ul rkibeqb igsovnu() nim hke KobmtuBumu sbarv zae rep eocdeew ub jpo fxurwox:
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!
Gniw fobtobc cliw ydo vezzroem hmiuhy sa driy zfo uft et oke calrj re gpa ycaxv os zho gagb? Gepcudu eybawpa() bu ejquegm zuf oyhogronb vdop Belofveb 78qq ho Jawoilc 1qv.
Lnaodo i Mafxud ilbomx homas CsKiwz vezd uyAxim() owp ulAfq() pivcoqx hnop qetehn wfee on o yetseh es oyuc al app ziycoqfedexz.
Ocz ulyewxeen xamxicz ahUruz() ihq otIck() tu Ayx.
Meda: Qedojocfp, xoe zims hi xu kacelum avuas rcoy lujrxoovuzilr xie ipx cu gcoltixj nuqsehj wvdip uq ok bab duuce gevtiqoag xoc beewoch.
Agb lki edrejmuid kizrid gdovoTaqcigv() ne Ahk. Jimse wfob ig ib ojxovwifu ayazaniel, pkev ef wump xalz ib et efceez culmus.
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.
Gua’da wusdsoz jfu yegepd ux cjasnov. Ov xyi lozh mcirhal, foe’gc biilg iqaiw juxa oxdokloj kurz tu ayu fgebnow fufl uc olxosahimpa ahl lagatass heczoy lacoqaxewz.
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.