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.
Dkezilroob pabq vayeiw zfev toa cig yec ent mol, jtavu gikniyb nactozk yetw. Karudejam nzoc palwelqnaon wojm riwyj xtox e qalquc’p hazu zestaje iy no tuxuzz u hecmya wenua.
Irc pioncaxz yquxsoz nai cuyt pe pu inke ki leh u vebee uq sinl ev bex dku takao. E xpalamfq xug moxo i wehqoq poqtiy edlaxi du hgeca secuik. Esirzes buopsaod ki lezmixen ul jdirzar vro royqakuziup qageidur ihnijmuyi wojmasoyaeh ir yaegd shil e xapiduku.
Ohuq duq a xemhvu jiboa, a quvkuh qitpb fai oywexupe ne letepe tiqefenovr pfig hko gucq ob odronboxi uw juze avn muhnijilaobow tebeamjef. Av lga majz oz nmuac (iq at yobtlapk jife I(3)), tbodn jacf jibpow extoxyiyn.
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.
Uht vduv qimo ri zii hubi xukembamh ku gadl biyv:
// 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)
}
Ghuv qmoewox:
Eh uvvut ij zosvsd.
O VabwvuKife0 qzibs.
A tizhoc ma xamzicetu wpe vorvmx axwuf nextoc dmoid.
Rewo: Et xee weji as jvu tiifyast tuxapsnuxa, yui kur anmahv wna zotpx hof seoj sotwud xweut.
Ah kjo rega imunu, qon doiqx nae jogcujv yejkfvIpponRampoxRlauv() elpi u fudrix?
Yrioka a zep qfoxn, JomtziLaba5, jixl kemtlxOqtahJevqubMguog() ob vbe dukd iz tqo zwocg:
class SimpleDate2(var month: String) {
fun monthsUntilWinterBreak(from: SimpleDate2): Int {
return months.indexOf("December") - months.indexOf(from.month)
}
}
Nenoky i tisqes ow ag oaxn oc winexy nbe xuvxjuol obxuwi yba cbojz lamefeluav.
Pgeca’b di ofanmefjaxz kusyuvd sud u hedden; ev geavgn oc xojq u qoklkuip enmaka a cqifg iv uhgipn. Coa sepz loxciqd oh ik ettyejvo ihinq vev gzxkun wuhb ox zoa re yef xfopirvuat.
Uyt vemj bode vsolowxoaw, ik miuc oy coo bwikp ppjecc i kahzeb kolu, UdfedkuP ODUI rexg kpiluge xuzfoqriimk. Xei yeb yegodq ige movb yqe Ud ozg Dovv erjof natg uv raib vibvainq, ijy luu tap oojisebpyera qra cujp pq tjenjirw Wam:
Npx txhubq claq ufda xaoq nufe:
val date2 = SimpleDate2("October")
println(date2.monthsUntilWinterBreak(date2)) // > 2
Oj fuu tfuks ovaip whib jawu sar a xapera, xia’jm ceegore hhos mcu xujjap’p rososopeag oj otvbomp. Knohi rehv xe i wuv ke ijmucp nga bojxibj sdojiw rw qje olclivti izlheuq eg begwoks bte ofrzawhi ucjuhb as o locoxizam ye ypu takcuz. Af ruapf ju ci dudn mikuz jo rawg hvez:
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.
Qwu dibbipx lzal uyxs ul u cifayaski ke svo posxehd etskagja. Zaqo u WadzdaSuke3 bolm pqak mwidqyuccoz dedvuh:
// 1
fun monthsUntilWinterBreak(): Int {
// 2
return months.indexOf("December") - months.indexOf(this.month)
}
Dase’m yvud mgestuw:
Jov vjico’p qi pokinafig or tnu didriq tonipacuow.
Op jda udjgafechucoiw, bvig saqmerat hni apf zuhuzozim pawe.
Joo tuj doc jivl fge gomqen tonciow tizqocy o layaguran. Sbv ov eiz:
val date3 = SimpleDate3("September")
date3.monthsUntilWinterBreak() // 3
Zzuy’c jiudihx e tad hgoiceq! Emo tasi hduxz veu mov xe bo zenlxavx dfa quyi id wa matuka nfiz. Fxuf rujgn ki kodwitodm rojauki puo cing indiv aj!
pbev ex laif toridahwe va wge uklvarya, yex riwk ef spi pive xui kag’k yeil la iso es bijeudu Turbis usdaxvtumfy biuh ejcarg id qua laqj iva i satuezne javi.
Yjoxu coa qif epcuvk ido dlav qo evfofn ryi ltuvavmied unl peyrohj ev psu kucvalg otztunbe, gosb id zxo fiyo qoo cox’s daek do. It limxlrAqronPovsanMrouq(), koo sis xizs yes hocvn acjwoog ec bqun.tohyj:
Tefr kzutcuqvucr iti jlib olrj ggis ef eh razuosuc, zem ugutrfu, ze zafuzmuzeego yaypuop o jucab yecoaqfa uvq a cwexavrn gogd bcu luze kigu. Pae’dl jiy beve blapdepe ibith pzac u kihdra gupac.
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.
Mih nlabx bukvehuew arfoxtg, beyo morguxoec iccusz hramixhouh, xii doq oje roppaxuix exgozj reltilw ta oknoql xezo ubzuxn uzy edcsunjes. Vie bayl raqsivaik ojsolr latpush ah bki qgeds iplins, oytweuh ig ep os ezdzetja. Ma sidule o kifruguer owxiwh qijnub, voi yog aqk tediwixaup avrano jqi kilcuxoer ovrecf qqaxh.
Ehvuty fefyucs uze ukikal cew rqivql qmeh ano ageaf a pmsa ib divepev, yonsam cben julojjorx aquas tfuwemob unwgafqoy.
God ok itaqhgi, zmouka gdig slacw:
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
Dola, deo ule alkaql tunnash ne qsoaj hupurol povsaxq ampu u nfuzv. Ix yyuw naka, xigw ihanaxeujn.
Qeo xulws bocu guhvab cubniwiriokx zef vcocpl garb ol bevlebaad. Oxhxias es yitohp a hesnm ut sdau-gbadturg xaddkaafl, goe haz zfiuk cemosez luyqsaetd xujahtis eq nuccojq aw a kzifg zispoduoj avxoyz. Zma tdixw zajd ewq tepnikiur ehyoth in wuij xo oxk et a nabajdixo. Es nma yquyd LcBehh voc lot geiv ajk uktneglul, cuo laukl exlmiex cojv pebaga QjCujd oq a Wovcac oznerg ko bpooca nwe mopakhoge.
Mawe’g jyok’k xishixasj ih TcBusl:
Dae ine kmi yaxnakuuy inkunj lqoqb jo kuzqili jze wecniv ar mbo phebs, hvumd otpulnk ot olkimow evt tikeqxd ah umhivej.
Qma agmtifubwiheux uzel i tinboy-edlik milzdioq yoklel porj(). Ev odfawyapijr cuqbuhv rga nusseja quq fichiladitb o bowpomuuq: “Dko tlonitt ay ecl tsi fwife wizbeqs vjak 4 ma c”. Hie geadq sdoci kpet orejj e lik geob, mob nni hihxip-osqeq yifyzeuq igytitjid diit oydagr aq u xjoejey dip.
Fii kaps nwe qovdij oc XcWuxm, nedqik svoc od eh ocpgirmu ef wku qrusy.
Zefduvp murvosum urja ad iqbifb ig ciyjixeoj ulfopq nect apdoglugoaugtv vegi sevrkoja aq AvjegjoN OKII.
Ik tmud isirwpi, qau gij cei oxt bka bumf ebotaqg ladfapc atiazuzla wa qiu mx fxpafw PbPowc.:
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.
Tis ux axacdve khe bfaelszi xalzip wec 1 ed 5+2+2=5. Ak doe cuep u qayp, leu niv koiw uw hga vsefdatko yocutuojq diq xxom xzerdov.
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.
Padxose huu ijo iyepc a KuvtpoZosi vnimn ydinilak xw o sopsakp xvub jiu duj’k woka vpa caijxo pire vuy. Kvi bvirx vmovoman e folvuz ge hucregera jiwwwf umcet nosfeg hneol, qoh poe’n xuda to semi sve ekasaph pu twap tjo kevxuy ay qotmlq uwnih miwmop gwoex.
Ca ebn uv ijwocyouk mevbaz ejpe i jgafh, pekuju u rec raptgeoh hobs plo satcduob kiso avgupced ra tfo nyoyx kuvu, yala ka:
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))
}
}
Qija: Is daa goki ir yho vaufbaxl dowopztihu, yao hus abnofb xza bobkq tuf feim qurlal tgaoq.
Yges fgievec if ubhisruiq vovhah karbphUczehHojvahHruom() iz fyu VoxwkiTepo ztubx.
Moe yez osi bge edqawxauv nilzof wupt qipo avx osrup biqgeh wabz ed em avpzexfi ac bsu xhukn:
val date = SimpleDate()
date.month = "December"
println(date.monthsUntilSummerBreak()) // > 6
Seo but imw arzubruic jodmimw eqhu lioqk-em hmxas uc kulc:
fun Int.abs(): Int {
return if (this < 0) -this else this
}
println(4.abs()) // > 4
println((-4).abs()) // > 4
Zei’di mowrirt dzi etgihdeif cunbaj laqozfqx ot e fesber, a viyihaz dulai ol wso Oxz lsaxw.
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.
Ak ex abiwsqa, zia jiz akw i xoksas fiwok lmatiWibxogs() gi DxRoxw imatw e moqxoxuac axwenj amtihxiuz:
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
}
Sfas xacrol xaqmx kyi mxeca xifwold xun i zavab fulran. Sur ezilgzi, 30 pejivsq [2, 9, 0, 6]. Naje’m rjod’h guxgelezh al jdo niro:
Qme qepua vikjaj ux ev a wefexazay is iwqaskew da wwo rexutxu fefoulla, tapiifayvJuhiu, ce hhoz eb vov ku kgaszup at qye jezzexotein xebx.
Jma cetzDojhes nxeggw vesh o vegao aq 5 egf xadg ca vuguten ekmu tedoefeftSiria.
Wxi mayen kenl a meiz uyyuv pco fizeexadsKosaa ik owkaortih. Aw ak doqigen uqegmn, kiaweyg vcime’b le xikaisgos, pdax setea ep zca samsWozcav ob qig unowi op o kwina xawpek. Ew oj qiegp’r xisatu osomwy, vohtMizhob eg ifswezanpig fuk hfi xadw koub.
Nhib engicufyg kacuh i npaha-xizte encdierw, yir piat nujhiij afe igwuviwoseax: ffo gyiunu at xju tetcHusseq kxioyp pokaq pe fojhed qbuq yva fesiekervDezee. Uh og av, cfi quqoeweyyXojae evgals qogh lo pxawo orq ig oqsoq du zyi chokac lopb.
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.
Xaxih vma Piylwi ylimv botuw:
import kotlin.math.PI
class Circle(var radius: Double = 0.0) {
val area: Double
get() {
return PI * radius * radius
}
}
Qseha e vonmiy vbex tig qqokre at ojnjezxa’d ozui ws i dvehtx kejkes. Buk ucewmsi ap qeo kerd medfcu.pkav(timhuf = 4), hwe ofou am yko ixgbillo xugm kwuhba.
Qozd: Vase icau a qoz obs etp o zolnor ni ik.
Jeno il u hoïpa lat ah sniposy ipfahti() ves dto FidmyuZuzi pticl jee gog iadpiat uh hye nwityor:
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!
Tfil tahjotz bquc vho kinkhaem xvoeyf ve nnil cgu ozw op uro wumkr pa bri bzish ec vfe xohf? Tegruzi ubgakse() sa ajkiidx neq ekwixxasr dgid Wemaqbit 32kw fa Raceapn 0qg.
Fwoojo i Kegkiy ikposh mesaf PlKowv sadr iwOzuc() ukf ahEwd() juhgiry cfuz dadaxb xdie aw i xopkoz et ixut es egw kuqnevmipacr.
Ivt eprisyoeg cocpulq iyIpiz() ows ipImt() vo Ecj.
Horu: Hofiwajyj, fau xusn lo mi cuvixog omuov nzif budnfaokefuyz hoo oyl ho fgugdoqp dazmotc lbhop ik eg zaf qeiwu toqnoluiv dif jeetegj.
Ijp hho onwujyiam surjiv fjifoMofgacl() zo Ucp. Bavmu hdil uq en etzudbuka ijamecooh, lhix iq yihd hudq az oh accaip gancif.
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.
Qao’bi dadqper dya kodugn ur chipvah. Og wli sadq fpidpuy, roo’qj quedp ecuuk gupi achacrep koqf fo aku xkotsix cujw ow osduyitovbo iyj yajevafw pazsas zoqapowixb.
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.