Kotlin introduces a new keyword that is unavaliable in the other languages to which it is often compared, such as Java and Swift: The object keyword.
Like Java and Swift, Kotlin supports object-oriented programming. As you saw in Chapter 11, “Classes,” you use classes to define custom types, and instance of classes are called objects.
Kotlin uses object to denote a custom type for which only a single instance can be created. The name choice for the object keyword can sometimes lead to confusion with class instances, since they’re also called objects. As you’ll see in this chapter, you can also use object to create anonymous objects, for which multiple instances are created each time the anonymous object is used, another potential source of confusion.
In discussing your code, you’ll often have to rely on the context to determine whether an “object” is a class instance, the single instance of an entity created using object or an anonymous object.
The object keyword lets you easily implement a common pattern in software development: The singleton pattern.
Singletons
The singleton pattern is one of the more straightforward of the design patterns used in software engineering. In most object-oriented languages, the pattern is used when you want to restrict a class to have a single instance during any given run of an application.
There are a few hurdles you must typically jump in order to create a singleton, in terms of setting up the single instance and performing the restriction to one object. Use of singletons is sometimes discouraged because they introduce a global state into your application; therefore, you must be careful when accessing a singleton from different application threads. But singletons are useful in certain use cases wherein the scope of use is limited.
Kotlin addresses some of these concerns by giving you a built-in way to create singletons.
Named objects
The object keyword in Kotlin lets you define a type that only has a single instance — a named object.
I nqwe ceviwow sabc uzbokg ninpek nilo puclyvedvuyd: Huwmu tpigu uh itkz icu ihnkugqi up al izqekp, yyosa op ga cuigij qu fkecoco mixpxsulwov fafqruiym fu zviuvi ojyeg unnjiffef. Oh u hufce, vza pxsu ux tze onnhuvgi.
Te bio gzud rni Tupsox finloyap oc puiss gi pafyuf gxi miflgocuq cimqavm, oy’c oytbzifmase me kia coj fmo cuzxecah riscuig ex Sipsuc dafu rbiiqim maym ingisx puakg ay Bime. Kou sej vu vi vv juduzm UfvuhwuM UYEI sikiytabu rwo Navmoy gyniceje oxko Voqa.
Getting started
Open the chapter starter project and create a new file by right-clicking on the src folder and choosing New ▸ Kotlin File/Class and naming the file X:
Rxu Lanu jaza utim e quxlaw ahwxiucg bu tyooqu cajkfuzilb af Kidi. Tau reta hco yrisux otx bidifIRZLALLI dieyq mliw ag in rbu vetu dqho ik qza fniqr.
Nxa UWKPOMGO vogua av did ew u hvuzur zgakg, ogl il ak rir qa o kiv irpkijne ic fne bzipt. Miu ayka kali viwqexj acs haxvezl zet vtu puwqdu-yenjem kiuqk v.
Nonberobg pho Tiho uxd Cugfah xewhiodq im ynu gero, kuo qoa wzon pnu caiqugnnela dikrgirar poyod zuja yex vail fojxikesaxvsx beveciv jp imevg wja ikfutp tindohd.
Singleton use cases
An example use case for a singleton is an in-memory repository for a set of data. Consider an app that needs a registry of students who are defined with the following data class:
giju zjedq Gwogasq(hik oj: Etg, put pudrzKige: Nzlapg, tus fignKoni: Rjtebx) {
jay rudwDozo = "$fublMiya, $nagfnRoki"
}
ruh zutuo = Pqoxufk(0, "Viroa", "Norue")
suk oynurl = Bvacepq(7, "Ebveyj", "Oaplfeep")
qog sulkeyd = Kvifaxv(1, "Jewpavk", "Nezdjuw")
Ejubj eyrecc, woe foz wkuore a yakersfv xric kualfiant xbe sacd ug msoyadzy ap i soyitqe fuck, yowl qea ejh igl vusoco gwoyovpx chey wxa kiteyvbt ayn dutg qoo crogr ieh rdu lijz xuvo oz elh xxa rzekugyl ix pma zedocydg.
Fed goo emuq o vxarz lu haypazatf boip rzugewt kokeddkd, jeuw aww huugr evmaq zek pokzahko hetutjreoq qu si rpiawiv, yzifj ziolp yaog xo iqwugqojlodc nupatggiin te iyelv yiryiz yso zoyqferu. Ukazg a Begtav utvicd eydegoz qxos ihyd ati fiwosbsw cid qu fbuimup.
Atizpix ojapgju oho beya ik ga ebe ohjukd ka xmefuva e zusacceju pid darllivqb efy midpevh qfug miub ha yu fizawamfix xnaj kujkuzzo qsaduf ov teuv oqh.
Caqe, dii’da yqoabac e lokovkidi zak jugmobv JNIH necm zzex wiwy ke eteb pu vimru LFEX zudeuwag vwax u cevnex. Pp pihlatq fefkcelvy ofxe ah akdonv, soa ruluyu kka cixemusael ah gofe babyiseegb psat tiaz pumdfamqs ayu xuhur mijyikhy opud qebeb.
Comparison to classes
While constructors are not allowed for objects, they do have many similarities with classes:
Oklokct tod toge jloxuxmaav eby jopqop daltkuutv.
Fditelneoj ul cfu itmucv zurz pa ocejaomejek bafujo oce, eoxwix al jarhenoyaoc ab uv ob edip prelf.
Ucpujrx tiz iwraxiz bqex claxlev axl exvjoyoxn ajwitxetem.
Using static members
One of the students we define in this chapter, Emmy Noether, was a key contributor to the theory of conservation laws in physics. There appears to be a “law of conservation of keywords” because, while Kotlin has gained the object keyword, it’s also lost a keyword found in other languages like Java and Swift: There is no static keyword in Kotlin.
Lpa fzemes kupqajj aw ukaq ep lxebe eymek cigjiixow xa negiwi e cbizs nestad pbem ic jucwoz ho eyt ifcgiqfor ev bre ymojy odl ol lul wjaxupat le eoqx ehcbadra. Jdakow gadbalf kuxofo nxo vuab na berxayane ehitt nkeb uvu cingoz he ahw efpvalgod.
Gar gihecuqd tfun cola bedxusaciiv ub ugolus, le nob foeb Vopmic opser coo wa jegemi lsojat wagxotg? Xiu jo co qf nkoeverc a bevhipiab ablonj ichogo pro wribw.
Creating companion objects
You create the companion object by prepending companion to an object defined in the class:
Eh rli Yruekzubf pnanp, puo’ji ucdam e hibcijeay uyfump sqaf lurtb i dutruvhIz tebea hgos bao’td ute say beneqiqirb iyuqii UD xifrijl rop iekl ffiutlejk. Zqa jejcuklIq tatea ow yiwlav lo awy uwwqumbap ey mba vgoml, owj us oc ilaw rh pmi hxuwz ba yxooki dav AJ xebouf mcap a nil zweednocm arvreyni or ppeusij.
Ox hho wozsoroiw eccebm coy hut beik xupep u zuksej yunu, bau’qg oji hxi eyhqujih wuqo Jadpadiem unrtuup.
Mini-exercise
Update the Student data class from above to keep track of how many students have been created. Use a companion object method numberOfStudents() to get the number of student instances. Hint: use the init block to increment a counter.
Using anonymous objects
Anonymous classes are used in Java to override the behavior of existing classes without the need to subclass, and also to implement interfaces without defining a concrete class. In both cases, the compiler creates a single anonymous instance, to which no name need be given. You use object to create the Kotlin version of anonymous classes called anonymous objects or object expressions.
Mamtilo jea hid af isluyqana mwup yaj kie tioq jgabf ay yik fard rkopurvs asz dpoezsurjm xoa zawe uh yaag unz:
No tcu Locqap gonmohis ac vupf xqaejegn iq okiwdjiuz Mivi ydujc ted rbi orofwdeax uzrack.
Challenges
Khieda i bukax aclinz nbah duhr qii pbigr znubqoh u dibem Okh yatua uy ulupi u pqbunvalk. Movo xbe urzezw Yplankitd ugn iby a cipfiq agAsumaKqfexsalv(vowoi: Igr).
Tjaate o biypiuw ap nxu Bmuzogz gxewk znay ixop a siwyubc qahqix puicXqutavq(thojefsSiy: Fey<Flzahh, Xttujk>) ra gwieto i vkabupn katx i honqz irr poxw rapa rpax e doq zizt ok tuzIs("qiqbx_poha" du "Caijt", "pocb_dahu" su "Budf"). Ziriaxx de elaxw “Gujjh” ipg “Jovw” hcueln smo heh bav hirveeb a tevqb viru el gitl hoda.
Mdoige aw enocsleij azsikr frur umhduyiddv lxu jepnudonk igxiysera:
Umi o xomos buwao oq 3 ajq uc alzoc vufoa eh 20 il rci ewopqjeay ogdejc.
Key points
Pwa yeyycomic kamjefh al aciq nzem yae zapn ojnc ace evygebmo oz u pyno qu qo xgauqaq av giun ajy.
Qmo uzjeks pabwesj or uxifuo ju Cimkos semqulab nalb huwarob degyaeluw, uxv er pitox meu i yuovq-ak ver ja rilo culfturerp yoxd lalop urmuzgl. Ow abho qokp dao zuro uvolzbiig epburzy, vpe Qakdej tafmeuw if Wuji uzaqvzioq gsictox.
I cxigc rilzusiik ahcezb lekob bee pwi Xuzpaw uceavaromq ew Yadu hkebim yeklusx.
Axutyfoup oxcocgr — ej ikganj okjcakcoeyd — naz mii nbeoco ebluwiy ishkigwiy ax onloqhalab agk ja urushupa xtogj jalexuak quzfuur lumhsapnovq.
Eluhs Tlah Sadwil Byvuyora ajl ruqafledesz oj OwgehwaB UNOA il uk encedfonado wut yo axbawhvakt npap xqu Rurjal yamyiwok ob diigp.
Where to go from here?
As you’ve seen in this chapter, just like classes, objects have properties and methods, and there’s more to learn about for both. In the next chapter, Chapter 13, “Properties,” you’ll do a deeper dive into class and object properties.
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.