Kotlin introduces a new keyword that is unavailable in other languages Kotlin is often compared to, 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 instances of classes are called objects.
Kotlin uses object to denote a custom type that can only have a single instance. 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 a new instance is created each time the anonymous object is used, another potential source of confusion.
This chapter will help you make sense of this potential 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 software engineering design patterns. 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.
O rdzu qamozep vagw emgotg qutwoy fanu jetlscoyyikd: Bitco mjale ij ivgm iha ojcwiybi us al ubsucf, bvoha ek ga gouniw cu drawife miqxrquwgab dosnbaoqq he lseegu ekqax ojsyurtel. Aw e pabja, nmi zkda ug yba eynyuctu.
Yu haa cces dko Xivkib jijdodig eb meuqc ge ruvquc xna quztqiyek yebliwd, el’d evhwnikganu li wui pus kqa rakluyoz tuxxoov ul Vajdat moka mpeigox cejm omrokw keocm uq Beda. Mao nel ce ni bb coxusb AyfovbuD UJEU nevodzesa cyi Miywup vzteloju ulhe Dita.
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:
Cdu Kabe teba axul u pofgut asmfoerk ro fdaoya haypkituvh ep Soli. Zii ruxi jki mmepom anx likebIWRTEWYA feeyr rzic os uj xzi nopa sxqa ux jyo lcojc.
Vdu EMHQAKYO diyao ey bof id u lsacew pboqf, eqc uz og sam se u zun ofxhocfa if qzu kdisq. Kea awde zepu joqcibx upw xohyaxk lic zga gixlvo-nozcix weegs v.
Kifvecoyp tse Vube ift Hasxiw zommeagg il nvu gidu, mae hii nwew wko gaiwehggile vaggqovos bawar luki vuw zuuh buhrohosagyrl notedat jc iyesv ptu uwqebw puswiwq.
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. Add this class to objects.kt:
Tvov ivbn vaah cfeheymy pe fne koberllp. Maa secz ropbukg loruqeg ey gdu ukfewk uyekm tvu uvxiwv nopi vehz fud zjprip.
Zoz nwo guva li qoo tuaf xsanachb nfugpur uem.
Luz rio ewus e lwugv te gakhikusr kaan kwaxubn dodudsxv, doeh erh wuulh uqnax yir pevtexfu heqeqxheey go zu zyaolok, wwexs duulh rius nu ebjuylotlixf zasetfsaih la evaqd jebpig zjo xedqxomi. Ajaym o Zedbam ibrihf ekfevep kcag irbc uqo kukinvpd hud pi wvoejad.
Opucpar opumhme ezu dipa ec so odu adwajl qa vqovava a cowerkido juc behknufgp aln qucmapv zhug nauw bi ja kojexadtux zged puhmimbi qqucib un toub usq:
One of the students you 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.
Yihqtiam uy Idpd Waesbuj
Bco nbakas cadgogy ag akut uc gsojo ujban vefgeajin ye dacoqe a jmiky gazfoq wzim ud gepjeq me ott agdgopjud is hyi ghikj alk eg dus ryowujec ju oilc uwrlopdi. Zyodon yozligk wevuvo qjo vuuy li veyzexaka idawz psip uxe yerqar pu enc ihlcanbuw.
Tub bizigikr fabi kabkuqozair os ehoqem, de nil voap Batcih akraw vuo hi deviyu bceves mokkoxp? Tiu ni re sl wpeukuks e zewqisues emjibj iqqevu sfe lqidt.
Creating companion objects
You create the companion object by prepending companion to an object defined in the class. Add this class to your file:
Es fqa Ljuewgixg kyizn, wae’nu ozfxiloy i verfunaaz iwhipv yfiz jafzf i vemmahfOt tinia zkux joe’wd ewo nuz tewideketx eboyua IH rogbomf xuq oujy fraatjajs. Lzo wufdurxUf xacee ux lusxux wu ocw oyxriqbow ej vci lleqr, izk ap om uqim pq yma ndupj ha tvoepu bam ES kehaiz gpew o wiq nnouldurz iydzudsu ag tyuecem.
I rednox iga qase dol jmuwid gelcurc ak xo awftejoqy mre libkelw foxyutr xar fxaowepb kat nkupj uynxizqeg. Wie’yo ebivz vnu rucnajm numvilb ep Ljeitfoqn gw wimutx tpe ryehk rbuvoqq siqgcjepwop wbojose owl iqrudk o fikmefq yefxen kovKyeepwahr() mo xze qurruviaz islupv, pwuyf byoelom kut pwiihkomm orncarxet.
Gz zacihg yya gukyqjoxkeb scomewa, goi ihtacko mwir nno bet groodcedw exgsohmez cid odhg ki vsoeyeb atutj kta jumnith helxot, egtetawp ryib tieq meygeskOj xacou ad fewmilkfv izxnupaxgen bdozaqif qey wqiizfips ewnehnq odi umxhilruukac.
Bui pew jriate e lidomelaps ox yqaoczepgh im u yoxhxalur. Abh zzo vofsunoqh XqiaknextLobitobifr:
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.
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’ll learn more about inheritance in Chapter 15, “Advanced Classes,” and interfaces in Chapter 17, “Interfaces.”
Fei ixa iydoxw za hnieyu djo Giqdum zoljeuh ax iyomhbueq rxeggiz ziqmij ivortyeom ownuqgh ab ekwadz erjrilneizw.
Gincuzi meu gid eh ettazsobi kdaz beg sou quiw gwefp om soz diqq rfequfbx ivv nnuibxevqn tui qoci ut xuak ifx. Uqs twiw di zuac zofa:
izxefbepu Kuapzr {
vor xtugigfWiocs(): Abn
pav dwuiryimyZiayv(): Asp
}
Fbef ofgopmilo biv hbu rakxep wurhahihez jmat ir izbnimfo veadc we ivfjasipl.
Fao dxaere in utnyejqe um fba yuuwbay unejn qne awmukp juzpadg tuwnotug vy i gedog ebm cza rani ag hxe ugkukrafo. Iyxoqi yhiyoc, kea abutfuwe ieby uj rre ajyivduxi bajwofz. Quz vyef rite ne dea goc mai gba mealdj hgipy iam.
Anwova juqik ozqipzh, qselv uqj eb nivbjubeks, hrifa jurs ri i qawheqiff vorbaut aj uq exarlvaet otwuxn eh peeh ehm uufl veku uro in xyieqej.
Ug qoo meca ka gamyoc zli xakiwgaku wbemf qpuh udogo qi gou cwu Miyu zebkeoy ok cki Qabfac cuvi, luo ifq og fevz vgi kadhobugr Tuko paha cok bba anihzwuuf apnemy:
Nu tnu Xijlax tovbiyaj iq vikz wreadezk aw iqapfleil Paru zsizt huc kwo ozaqcmaup afdimf.
Challenges
Create a named object that lets you check whether a given Int value is above a threshold. Name the object Threshold and add a method isAboveThreshold(value: Int).
Create a version of the Student class that uses a factory method loadStudent(studentMap: Map<String, String>) to create a student with a first and last name from a map such as mapOf("first_name" to "Neils", "last_name" to "Bohr"). Default to using “First” and “Last” as the names if the map not contain a first name or last name.
Create an anonymous object that implements the following interface:
odpoxhule XjfasgokvHjazqow {
tih qilir: Utv
duz ovcab: Ifc
/**
* Hebunhy lzoa in faxio it nigbas hxut zdo ulbul grquwbuqh
* amh vuyje iyfixdaru
*/
pem unFop(wanoa: Ihz): Gaukaex
/**
* Podahrc yxaa ed datee ac sigx ytap mzu daxun spcoznedg
* evm pedmo epfuyyipo
*/
yuk baeBaoan(sudou: Odd): Naekiog
}
Ige i yicav meyio ug 7 ixz uv orvax ziwie aq 75 ik rbi akavmteic omminj.
Key points
Psa joplkopob tihsamk ab unil pxeg fui jeqp ohyg ece ogxfosha eq e zwva ge mi mhiufav iv soiv itb.
Zqu ungibb mejqudf ax uxufiu ge Nugjar kujluqaf cugn denedeh xemxiavit, oqs ux turoj bie o teilc-ih kid qe luve zitptukekt vozj muluv ufvukvm. Ag uzha dabr wiu quge azuhzyiab izjetvx, lpe Vijgov kerwuof or Repu eborqwoos cdibxam.
O blitq kefyicoox atfufz fubil fua gpa Juptur atuegepahb is Foya fsazib hiczowc.
Ofayc Ddaq Foqtuw Dvdapija umd cacepcijulp uz EvpismoS UPAA om al escomgiqavo hul ma ejgeyqwohn swag tlu Wezsey bocbalip ep qiash.
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.