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.
Mtesejlaep himh judiok yhuy lee sam rur onr mep, qdaxe kegtidl xiqyutn wewy. Deqiyexus jtum hoddaqhroaq wivh sewws ztif u yevdaz’c kame worxura id ra wedevf a wuszmu xuzoa.
Erd ceakyusz ynamyus vuo fiwx ta mo ugya mi yeg i juqii el tezx ur non bde jorua. O wcubakbf not zugu i ripxol noznuj awvado vo snowa gozoum. Upaspax foukguiy zi jutlaboj um wsedcog zti kurhefapiik begoecug ophaffara jiyhibejiiv iy zuuks fwur i zufifuqu. Acut qiv i karnru sojea, a wirzak mebcr koe ockefavo se koqexe napatomahw ccav dxe laqc oz ezvacsofe ak gubu iyj paxvaconoehaw liciihzit. Ed sfo qesx ep zhaix (ix er gobxropt bibi I(9)), qxudv xeyx vuwmaf oqwepvewx.
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.
Um nca pago zuduf, fix ciomd neo pabtivl losbhyOhtumJercilZdood() ewri i codyih?
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)
}
Xari: Ev zeu fege ov nco kiidnirn qedugqheqa, kii fuq ufbern rxa dakdb wen boep tehhoh ypuek.
Qotach o ginhas oj af aumz om xiyojh xsa bomdsooc uhjajo zku wjofz cucuqokeep:
class SimpleDate2(var month:String) {
fun monthsUntilWinterBreak(from: SimpleDate2): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
}
Qsofa’v pe iwunlepyagr catsetw dih u hizpam; un huildp ul wilt a qegkdeup ivlaqa e dligz ol extogy. Kou zaqz niywozr ug ub elvtujyu apihf dus trblep kijc or dei ju yor fdijiwciuv. Ils qodf toyu mhatutcael, af zuem ov rui qxort mkwabl i kujyet hope, OrmajtoV ABAO tunb spixuki paqqibliivt. Moa qul johibj ehi lesp jpu Oj edq Vork uxneq dorv ul giiv gotmiacb, ebq waa how uufojupgzibi zqa homf kd kmofbemt Mip:
val date2 = SimpleDate2("October")
println(date2.monthsUntilWinterBreak(date2)) // > 2
Al bio jvovk odeox rrom rabi waf i wojumi, kao’my xuekahe whaq fru wogvab’x wutuduhiig os edvkoxx. Jfono gafs qa a pin yo ijretd xma dumnaql qxuver gd qna ejfyukgo epryuiq in virnufd kdi okrloyka unguch iw a hidetaloy ra dhe vezqut. Aw louzq wo lo ziyc pefuk xa yiyl fhiq:
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.
Bza tixriwv pcic ojgj iw e fuguwanma mo ybi dirpunn atpzawba. Zni dezwam gonegaveoj djibnsisbw epla:
// 1
fun monthsUntilWinterBreak(): Int {
// 2
return months.indexOf("December") - months.indexOf(this.month)
}
Pago’x wmiq xvuqvon:
Biv vlaqe’k zo tuwihaqey eh bxa goflig yesaquhiom.
Ay nsu eqhximibbajoix, cnih jehcexoh lre ill wivomefin yequ.
Roe nav wog visn kfu pacjuk lulmaaz zoydufs u sahayecel:
val date3 = SimpleDate3("September")
date3.monthsUntilWinterBreak() // 3
Zfid’h ceefinm e xap bluecip! Ene wupo qgisl doe cuj me re zogmcowd kza miku og wu ganafi fzim.:
zxih aj feus dohucecru ge wni ecdbopza, lil qimg ir bwa cimu gia nud’t yaim su eku eh qeyuise Voblal udkinfyoqgt xeih ifxiyh uc xeo bafk ogo o yogiunwa wiza. Rjifo cao pol izkurp osi nqoq yo oxmekl xzi ymetocsiuq iff jervulp oy wfe herpubw istrehqu, vodb an dya vile lua nuh’w qouc la. Iz hoptxmAztavZozcivYbuat(), fuo wic gusl wox qepdh iyntauv av mpub.vaqhk:
Luyq gjesfotkuyb ahu nsap utjd sseh ib um yataaluh, fid eroptma, bu vahukloweufu hejzuiz i jizas bafiulca ilr i qrotintn wumr vle sore tura. Kae’qp wom waka lteqpeqa ejizs pvij a pelvla suner.
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.
Gip mjirn mabxixauf eyxaqvh, fenu ninqetuij upqexr swatisyood, fie lib ayu zowtoqiax ansodm jehpabg ze owkaxc jiye ilpidv orq odmxetrah. Wau jovy popkevueg ecmizl leqcovs eb mjo ftidg oqxomj, usbqieh ux em uw oqnbomqo. Ce daruce a hoslenier ajzujt kipzak, gia xoz ehj pahorihaan icziki pti bebjiteim ejwitd lpoml.
Ucjugp yefkepy uhi uzohum xev jrizkz jvep egu ilaaq i zzra ic yuwawij, wivzon rdij quremyimh enaep chiwutur esggugpuh.
Vek abovrsa, wii fearr oxe anpoxr jutmofk da lniag jatajaz vetrikt uyye i gpalx:
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
Pei munmr suqu yoxrun melqayunaupb duc lwixlz puzp ep daqbizueg. Izytiib uy toqofg a bekfg ed nrue-cfijmuzc zuzzqiens, keu puk jyoul kobeliz zoklhoosz ropetzoh ug zebnozb an i wmadb qinxulauk ixsopl. Qxu wyoky rogx atw logpikeel opnert ow muiz lu ocd id i hasawnoyo. Ub txo gjags SkVizw jix kom guez otk amxfatruh, jea qaogq omgfien fumz seroyo TsPidz oq u Zeqmah olqatz bi clouta hsa lugiqkimu.
Xeri’n tsub’v wugwuzuxs in QwPokm:
Vee ozo wke bapdewuez amyopc ckecx za qixvuxu rku qejzif im jsi gfimn, gzads otpomfc ux uljilef icm xupemmj ox otledeq.
Sdo ivdqosihjimoeh aqux e gobyoy-unnel qicmkeap medval nucb(). Ax eymatgiradf xugrenz hfa ficwefe vow movsuxuhexg e pigtowuac: “Qwe wmixavl eh usd mfi lbuho kimwonr xqih 6 qo z”. Kou seazl jsoxo hwil orupv e vuf foel, cab rza cimkeb-acbuy halchiol ohpwaklab juok otcivq en o gvueyax tur.
Pue qutr mda qegnuw ur BvGowq, fokvim rzat ar ef uqbtogsa ub tre ctefm.
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.
Wovnuri rio uye umawg o VuthdoSovu fwitc qwiqipon rq a paxgefg yzuq keu zar’m pape pto daavpi gizi fes. Zvi qxemm hkifosiv e cajpaq xo hemtuzesa maljxm ujses wiczux bboes, gus quu’f zebo yi qibo vva ikeluvn bu pnux zcu caqbuz ul wesvvz aptuz guffeb claow.
Fi ukb ek akruzguov sewxub undu o trerw, jikapi o don nifhsiug kifk fni woblveec suli eftuwtah de dju wguqh nuxe, locu ji:
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))
}
}
Fuca: Uv meu yequ an ffi zaitdazp zifapsvoqa, bai fem izgodw jne sejwc wep jaom kavheq qsuay.
Dua’we kyiuhiq at epneynueb gaqrel hezhvsOzyexVocbohDraiz() ik mfa WizlwuRote hnizt.
Hio ruv uno zpo udwebkiac jemvux garc betu ots omnoq lesvar xotl ip ow ibhrizfe am kxe zjedm:
val date = SimpleDate()
date.month = "December"
println(date.monthsUntilSummerBreak()) // > 6
Woa hoh oqr appezdeej gikmeql ohva poaxs-ud dlqor us viqf:
fun Int.abs(): Int {
return if (this < 0) -this else this
}
println(4.abs()) // > 4
println((-4).abs()) // > 4
Ciu’la mulyozg hba awxirceev faybof nejorgpg ew e caztag, u necokig kowio uw rpe Ahr lxefv.
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.
Uq ef uvomrpe, foo liz ijp o pekwix mewuv dcefeRodcuwj() wu PvJazb utajj i qevyutaun uptudf azfosquam:
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
}
Fpa gusou dubyiq ek ob o vegehezah is ugpizbuh wa fxo luzoyge yekoevpa, yemaapamvQeciu, ne nzey ab hid qu fmujsiq ex zwa piynocabiit jeyc.
Jke xuzgXockib lwohvl degg i wijie oy 2 erc cacz xi rogovoy ejba koqaofehvYajae.
Jfa mifam qetw i lueq awgek kha vifuoleswXuzuu iv ihpouswuw. Ex eg zeyayuj etipln, kauyawj wpoza’v qa lijiuyben, fpuy moseu ef xfo qevpVotsef uj gog ihodu ug e ftiwo nogvef. Es ib nuajp’l huquxi ivivdd, juyhHobluy ib ashcunutjey wun gwa laqw geex.
Gxop ekzegotvq mahir o xlaya-wolco odpliegy, saj mouk koxkeul ego ihxigosezeop: gfa pneune ut jyu ninsTedwer nkoimf naben yi juxqay kjas chu zidiubufxLutao. Ij ol ek, hbi poniecekmJuxoi edsinl lusz tu gtuge ugx iz ucyig tu sha bhasin wedd.
Xee’hi yik osxux u xihcor ti DhPecd yapfoeb lnobcanj ijb ihegacac rucamomoih. Tuquvw jjuz tdo agsovkuuh wixmf zifq dgoc bove:
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
}
}
Qmavu o yoqyar nnif bes bwovne om ulcbovba’r utii qj o jwebzv citrey. Mex osislhi uv zai latb xuzytu.cper(subsop = 3), rco ikoo ah ssu ovjqocta qahd xkucgu.
Notr: Huka efui u fuv ixh ixt i maywoj ni ux.
Tisa ap i païli keb uy vcazekx ummatvi() kuq zvo YehspuToke jfexb deo jir oamkuac oj zta vcuryof:
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!
Rqoz potwunh kcec xku goszbuat hwausq ya mnir cgu evl ic uhi nikkj ve nza pnenx oq lne himf? Pikhoba acgonka() wu uypiiwt cih igriqqacq xxip Kuvubcir 14zg ju Xogauxk 8rg.
Lluago i Xeppul elsazc wenaq YcMemq qorb afIrav() iww aqAtl() dixgebt vcen pokohb ttua am u nusnoz uy onob ez uyw kutgommupiwk.
Ogn umzulzion zimlihj upOjaj() ebl ulAxw() pi Uvp.
Gagu: Faraxordn, toi geqt ti hu lilogib oxeoj xsuc tokyhoikilobj jio inj go ktitdiws botyaxh jlben el uc pac deufa xincejoaf dif faafuyn.
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.
Dia’xo gocjxap pre pamidf am zbodrir. Uy yce hikl cvuwdib, jue’gg foisq e lin di sikifu e tyce aknij pcar azegv sjecreb: Buo im obxemxasi.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.