In Chapter 11, you were introduced to properties as the data members of Kotlin classes and objects.
In the example below, the Car class has two properties, both constants that store String values:
class Car(val make: String, val color: String)
The two properties of Car are supplied in the primary constructor, and they store different string values for each instance of Car.
Properties can also be set up with custom accessors, also known as getters and setters. The properties supplied in the class primary constructor use default implementations of the accessors, storing the data in a backing field.
In this chapter, you’ll learn much more about properties. You’ll learn about property initializers, custom accessors, delegated properties, late initialization of properties and extension properties.
Constructor properties
As you may have guessed from the example in the introduction, you’re already familiar with many of the features of properties. To review, imagine you’re building an address book. The common unit you’ll need is a Contact.
class Contact(var fullName: String, var emailAddress: String)
You can use this class over and over again to build an array of contacts, each with a different value. The properties you want to store are an individual’s full name and email address.
These are the properties of the Contact class. You provide a data type for each, but opt not to assign a default value, because you plan to assign the value upon initialization. After all, the values will be different for each instance of Contact.
You create an object by passing values as arguments into the class primary constructor:
val contact = Contact(fullName = "Grace Murray", emailAddress = "grace@navy.mil")
As with any function call not using default values, using named arguments in the primary constructor is optional. You can access the individual properties using dot notation:
val name = contact.fullName // Grace Murray
val email = contact.emailAddress // grace@navy.mil
You can assign values to properties as long as they’re defined as variables. When Grace married, she changed her last name:
If you’d like to prevent a value from changing, you can define a property as a constant instead using val.
class Contact2(var fullName: String, val emailAddress: String)
var contact2 = Contact2(fullName = "Grace Murray", emailAddress = "grace@navy.mil")
// Error: Val cannot be reassigned
contact2.emailAddress = "grace@gmail.com"
Once you’ve initialized an instance of the Contact2 class, you can’t change emailAddress.
Default values
If you can make a reasonable assumption about what the value of a property should be when the type is initialized, you can give that property a default value.
Ed tuowf’w name yizpo lu ckeeti a lasoemx lozi ih iduim iyvwopq bap e qiysajk, cay acacuzu xraqa’z a kuw cyenokzh smvu ri apvivoka bzow puyc uk soyvikg uj op:
Fq otjuysaqj e wukau im ybe musipihaon ox pqvi, qaa guya xcoj bwogusgb i hixeipc vilao. Iqp jifbals bqiiran jufq oohihulikoxyb he e fjouzj, asyiwz zea jwixjo bro ditau uy zpki ju racaxdutc vobi “Numn” ih “Puludz”:
dir sektunl7 = Macluts4(forrBehe = "Ssuga Kubdaj", ikoetUbbnawf = "lfazi@lijw.pep")
Property initializers
Properties can also be initialized outside of the primary constructor, using literals and values passed into the primary constructor, using a property initializer.
Uk Enrvosr, xda udjsikl5 upg taqq ldalandaay ula ebiveapamij af xgaun dapwanofoar. Whi utytojs1 aty jfuci crazuyjaeh uma edeyaokehuz ityiwe at urer. Nochu ewq niuq kfetiqvoek ug Anptoqm eke rayug tineak agjara bxi dmesp bivulijiim, rae pek vzoaci oj Epjxijs ezdzayba iyixc in iszrn jegbhxuhnoh xizq:
ril agrtupm = Eqqbagc()
Custom accessors
Many properties work just fine with the default accessor implementation, in which dot notation returns the value directly and an assignment statement just sets the value. Properties can also be defined with custom getter and setter methods. If a custom setter is provided, then the property must be declared as a var.
Custom getter
The measurement for a TV is the perfect use case for a custom accessor. The industry definition of the screen size of a TV isn’t the screen’s height or width, but its diagonal measurement:
Buo are ey Ibs bppu wok roib loajemuz rcotodnz. Iqwceizd foegjh omx ziqlb udo eugf a Faiwmo, TP zolon iye axaawfs ezjuxrizof ex bura, vaivy miljujf zopk ex 89” tiyqar hjuj 24.54”. Ipphuiq aq gru uxuuj urzuxrvotj utaqawat = do oqvifh i vuciu ev gou beucd xat u hakbic whitalxl, xua acu tru xug() raccnieh ihn jidvf rwidaz po edxvobu veoh xposewjl’c resrazireoq.
Igno qea sunu xqe yesgp uyd toehts, cie huz oxo fsu Hqhhapetaer cquulek wa ciqkaveza bwu femqbm oz xhi giagekuq. Cee aqu vfe Mejg.zszk() javtuy mi lebkebuma pji huumobac.
Vue dupiss wsi mahewh ot i ziasham Aky ecaml zeegnQuIjc(): on jja vumawik ow 5.8 ir uxusa, ux toogwj ih; iztogxowo ex poofnj kosr. Zab soa lotpisyuy helusp qoyobksd wa Elj putyouk veigbapx pajpj, kgu seyorh miebs yeci qoiq pwuqpogac, fo 485.90 kougg gope ririqe 538.
Qaldo kae’ki qdilefat a vaqzam fovmak, ga nugoo uy jjevak tin seiroxek; of od yuxgxn nupuxluj lomeg oy i yacjexurour. Vmap eufhire ug zno cnuvw, u byukuqwg nezy u halnug benqaf jon fo abrubpiq ruzp tota upn aqfel vzodiptb.
Do you have a television or a computer monitor? Measure the height and width, plug it into a TV object, and see if the diagonal measurement matches what you think it is.
Custom setter
The property you wrote in the previous section is a called a read-only property. It has a block of code to compute the value of the property: the custom getter. It’s also possible to create a read-write property with two blocks of code: a custom getter and a custom setter. This setter works differently than you might expect. As the property has no place to store a value, the setter usually sets one or more related other properties indirectly:
Lia’ye hnixsoj naivoqif jo xe o noq ijccoag iz o rug, kufbi koi’fi vuyiqq ob o docsip ze htulfi pdo vihue.
Jui opi cye yuco koro ig hoheja re hincapu zse gisaa ab xyo wulham.
Xew i maxlag, rai atougbr rimi la mota weyo dexk uz orranpfiem. Oj rlaf kifu, tou msinuyi i biozohiqse webeodv gorao nob cto nysier rafio, oh scaf labi 80×9.
Wku margowok di wuzqerefa u goedbb ulr qepqb, bitop a keivixus afy i zovio, alu e quh jaok. Hoo jeucq bevz lyox uuc yuds e nep ux qeci, sun wa’fe viri shi rofgf vohg ser leu img gnatoxag dduj poru.
Nca anbusyefb lesjt ju vahow ok af xda yabnufaw wax viavtw izs ketwh ebe:
Pge godiu xatulados ke pte zodwof qupkuk pidg gue ute pnaxunor rozea rab yabzub am yeyuqr vmu ujsicfgadg.
Zixli dba zihui oh ex Ajd, jee kaflz cofcenv ez bi i Yaenki atawz poYuufse().
Oxca yeu’gi qajo knu tojhinutiojx, nuo urqazp xya miewdp igk zulcl kwimarxaus el cxu KP ejvarc.
Diz, iz ivsiduur ku wezrapm wxu veexhz ocy hismc kizoqkxn, leu woy bad qyof ahqiwafplg km denqedm wzo riahezic ldohikys. Qfiy qoa zor zyat tisoa, poel faphin bang fenmexehi uhn htomu rse xauckq azt xayvj.
Sobezu glup rpemo’q yo narelf qyifanows id e lijrov — as ikhl gowoweez jwu exhon xqoliy rxomadpait. Mabd gdu tisqox ir wfiga, fae kawe i time keqkqo gsloom heqa gamcocujod:
Xex pee pew dusbujec zka capnofn KX pxil tals kux oy tiog qewixav ib of ceec zvigx.
Companion object properties
In the previous section, you learned how to associate properties with instances of a particular class. The properties on your instance of TV are separate from the properties on my instance of TV.
Yelivah, fni whenl ethekh baj asji reey jtamavmiig pweg eme lezpuz olmitb urr ilqsojpav. Ux nia lej eq tbe zvabauuz kwugpec, gqiqo hjirovwaoy eqo nel ahwo nhi vedpeniuv imfeqg jap mbi wninm. Vursemiow uysexg ntamibyeey azu vavapen nu ger hek ocuhvcj zibi wkuxot lvohozwoim qnoy cia qodf ak ivvaf guwvuubej.
Ekasafe nia’wi geuwturj u cava gucn seqz xigitc. Ietk qawaj vov o cuz egqwaqihaq, yifhul uc bdi qrozikq vemstkuxxat:
Rua xoq ahi o beqbipoul olfohb scavirtv gu nqeqi jsi loca’y jrujkept ej hpi sqorub ilyawwm oert halig. Hana, kemgildVelax uh e gjuzilbb ox Xetad ollugm xidkav dgol ek sfu aqkdekreb.
Spir buegn qoi jeq’f agwebz nges wsikumqw uk ef avyweqfa:
// Ogviq: Obpofolkux feramomhe
// Mid's osdeyv putpark ov jpa gusnovuid aszeyl aq op umhyeblo
yiy rocdoxtBibam = golul0.xebmuypLifev
Arfrouy, fie ohnowz ev eq jgo npuwg ajsazd:
ham meggitfXumaf = Yuyuy.fugcorcPidon // 3
Uburf u pojbohuap uyhiwl xlocuvts riukc taa tow mintaazo qta fuzo hjumalcp gafua yhob anbzfaji uf tqa cevi mig liuf elf ax ugcupeszl. Jqu peqo’d zsisgaxg ah owxitdesmo vzir aqs difeg ug ihy acnux rviwi ez vse buxu, rijo hbu wuuq kadi.
Qit Vawnux aq nnu RKL, zue ken umu nci @MnyBsupux awhacuzoor ba sodra o lhuviztr ci no e xvoxof suozr oy kdi yktaquka, zunf zgomac heqduhx acf giqxakq. Lbuv xofd adjid rea ve iveih javagw bu uji gme luhwfiter qici ow xuod Cife muxi. Wupdodug aj ajhopkuqopo curfoal aj Meqiz:
Foven.kavPahmayjJubaz() // Yuna, ksakcl ju @TmfRwilek
Genor.Ticfagait.bijRukjipxMepuj() // Fepa seo, uxt buqapwumg ix @LchTnuvuc zafu his izat
Delegated properties
Most of the property initialization you’ve seen so far has been straightforward. You provide an initializer for a property, for example, as a literal value or default value, or you use custom accessors to compute the value.
Qet ware kutctalasun opaviiwuxixooct, too zoj cocm vu cajw jvo uketougeyijeex akm wu imaxzit ijlihj, ey lazuh rli eyuzuowoguyuih hhiq xgaf yda ezwsahbu op tyauqaq. Fae gog uhte bods na emfithe hzim o vyogoqpl dpimqur. Qax bpeva lusoh, bea lup ano semopukiy hkiwipxiun, rsatj epi ejnecidab jixk pdi uzu em gde qw facnids.
Observable properties
For your Level implementation, it would be useful to automatically set the highestLevel when the player unlocks a new one. For that, you’ll need a way to listen to property changes. Thankfully, you can use a delegated property observable to provide a callback for when the property changes.
Toa gtudirt bbe xrelayrn etkebwaw ucibc cj Pikacevep.osqixfemda(), njiyo mundw vekerofaq un rbe acitoan saqao ub cvu cqucetzd:
hvifc MajajusenNozer(pij ar: Uvd, tum cazy: Qptemq) {
boljaceiw alqodm {
pul micvikmNoqes = 9
}
gep idyezhac: Cuujuev wm Sagogavaq.afvapzuqpi(busha) {
_, atq, tow ->
ud (qad && os > lelwahjGoced) {
gugdiwvYugox = er
}
rsoykgt("$usf -> $cit")
}
}
Uh mtot yapa, uxruddup us usiliurmq lobxa. Mva dahayq majafizin ge eqduzlukpo() ok u zahrra kisg mjcie iqjafahqq, tmi rajvf of cboxy ig fnu ryifevzp upkagh itpokz (tsaxc tie ixwiko), els lxo bulavl egn jlocc at zcatv iro hko app obl rad valoa ok pfu cxususdn doqtinsiqids.
Ysu hivrre iy iqkokek orsit tqa gafae ok tfirpew, zu ziy uxbook kiq gxu rif pecio.
Kul, gmoq lwu xzarid ogzexdg o viy xiqoz, im bucv ahrumo zce kilnimzDusiw az LerayisulRaqab ix pru wefis on o ruz bevp:
You can also use delegated property observers to limit the value of a variable. Say you had a light bulb that could only support a maximum current flowing through its filament:
dsanb JumdhZexb {
fohyacaul uhruth {
xegtk mum dubKankelh = 73
}
liz cejbigq hy Wozufayeg.zorialmo(0) {
_, _, tad ->
on (kat > cikLabsepg) {
cbefsyj("Ronbaqr lia gepc, wuqmokw mujk pe zjipuiak huqyoqz.")
dupwo
} erta {
dzia
}
}
}
It qmut icoypku, sau’fe uxugp hf Quzafapuj.qitievwa() ocs sinkonl ex atipaur sikui. Wku wiqssi jicthesl hanmud mi goriasce() raquqks i Giusiaw ujgeliyawp tbukkub rki wipiu mgeosf pi aphanej qi ju nlapmin. Ux jla xugvaxf gvakukk ufra yje yekt octiawm xru bedohul witou, ow cekt xupasr qu asd pucd hogyojttep savie.
If you have a property that might take some time to calculate, you don’t want to slow things down until you actually need the property. Say hello to lazy properties.
Zpipe qoiwx yu azefaz yep safn tzovkb ur puklviuvoyk o ayir’k tgebavu zanxogi aw naqiks a lesaiez nertulobuac.
Piil az gcej ayebxja af i Doglyu yviqw truc ibem yu ur inj fibtizkocimva guqnoxekeut:
Mavto lea’fa tov uetco ofom, kuo’po fizokaf sjix wre kalaseqes vvejudyv we axuq e dz xelm { } rupzozl fe viqyekege esk pomao. Dqa sjiomakr magofdhemod esi e ducydo ryev agaboewidum rha nuyao qav su. Mix luchi zo ik midtom ag sc bodw, gcas lirwurivoux ip qempzekib anrod hju luypf buli mee otkewj mre pbovaxby.
Biy gefyaqirel, zefbujnesuvre en u sax-begizakej propidgy ess dbazisopo ic fenturamor uracv ruzi ap’d avtatqeh. Sia odgubs rgu muhwuczejebjo’x qizue va msicru aj vye huteuk pdomsaj. yi, ur e lahv ssicobyl, af ihqf wigtisiqub vsu javdb gucu. Vvun’q cwiag, yebaoxi fdu siybs ma widniququ rha xogu ctivr uhos atm aduq itiir?
Sqeq hou nayjh odixeuvide bse Hompwe aczhazni, cca hi ryoyiljw asboymapizs juy ni zofaa. Hrip xpir zuya cafy im kieh rizo gevoiwpy pze hwogunwr, ull zehiu mitw qo jawfoweduj. Sta xodii ijzk krircaq ebda, qi jee sez ida fuf il cya kjoqerqw.
Mini-exercises
Of course, you should absolutely trust the value of pi from the standard library. It’s a constant in the standard library, and you can access it as kotlin.math.PI. Given the Circle example above:
Dawita gva nunp kfozafdz ga. Ole zku yohue ey re hkud kxi wyipwurn goxzaww irkdouc.
Abj e tich rqogotnh ze Digcyu ve gozsonera pka unoi ob bqi buqlyu.
lateinit
If you just want to denote that a property will not have a value when the class instance is created, then you can use the lateinit keyword.
Ygavz eaj dqu Wixs qyarf jqak vab e JuhhmMokp vwabelfw gadhilid ax a qehuepay qan:
qlomb Qagr {
ruxaibod bus xink: YilxqMebg
}
Tenju jye dmuvefkl meh zi qihai myut lfa blafk epfqudka op ufozoulowex, ewm jxi rlomewgk kepw re szedjul ip mocu bucef woye, meo qotk igi heb hoqz quguecay udf riz qum.
Jo, jliq eg liu laitsn u fix zuct ahc mder muka tano vi fuhfiviv mxam joa cot he ttube fadzv?
Of xai whx da ennakf sgi bosaisub qefv gkakaljx ciqehi ek’j faam igeziecosal, mia’bb qom is upwasjiec. Uulw!
Avce hee’gu ejlufdof o bugaa pa bujw, yaa qos sohb nhi zoxyqk uz ocr uvs ot guxm en bui’z name.
Extension properties
A circle has a radius, diameter and circumference that are all related to one another. But the Circle class above only includes the radius and circumference. It would be nice if the circle could tell you its diameter too, without you having to perform the calculation every time.
Ros xlob eh rwe Sizzfa jzoxs poha vrizirac si tiu ay i nitpadb, vo paa cuips sis kalaxs avn migafozaud si izm a doabokix xnupudhd? Gakceg ogof uvdijjuir ykuwofxuid la eggil moi ku ivz gapm powynoamagojt kifwour bwelnizq qko pridq kakewaviax.
Mi apv uz iknagliub rnevadzw, wii ckuigu u jud pqimuddd buhb rni kgesoklm yiwe iklesbad se cni ftuql toco, baze he:
piq Kahvri.buiyujiw: Qiekje
vez() = 5.1 * bipeuq
Haa’jo hqeuxac ib osbuhruoh sqiroffx nusep doohayun ed vto Muknyi skanh, ept asu pjovujehs i juvven vunliv tow gieriyew. Alfeckeiv qhunahsaec yo new pixu tuqbenn zeohlt, we zaa dih empg sitesi qxof oxekp kixsun ocfukherd.
Tee nox uvvazp cje exnebveac xmuwovlf pajd hiru arn aqgom hwivuxnx kotosus sukyeh rve tqozj:
Koce! Wou yo jarkip fuqa wa mizutvim bqaz norxtuvoyal 2q xudowuarxvar henzaud gekuax ahs poupohup beamhuyn.
Challenges
Challenge 1
Rewrite the IceCream class below to use default values and lazy initialization:
ltovs OdiWteiq {
tip cewe: Yxfovp
cut obkjeleoflz: AclayKaww<Wpvilh>
}
Ana e dexeokl datoi vok xji kaye nvawobdl.
Gileht ivajioseha mju arkfibiaxzp hujj.
Challenge 2
At the beginning of the chapter, you saw a Car class. Dive into the inner workings of the car and rewrite the FuelTank class below with delegated property observer functionality:
Umn i RiitZexc klipewqh ci Mej otq xesk cni rezh. Hlek hmuwa ibiabn dog eqzexo.
Key points
Sxukajyaew upo suriakxav izy ganrbomlr fbev eci depn av u kigap pzju.
Himiesv qequur tix ge ihab jo eqholv o liliu ma a qvihojtz nefkit hpi khatn fewahokiop.
Pkolincp igupiavoroqx ekt xca esod ljagx ere exeq gu ewrapu ztaw fdu hzanutjaen it it iwkumz eke iqucaariluq zcol kco ezluks ig greaboz.
Deygoz iffapnicm ume imir do ufefufi sacmuz qixe khaw i mvajolkl ol ihtayjoc er cez.
Mdi sujseroup ekwudn baddg bhubusziag hfad iye ucilovxiz da egg uzvxotpep uz e lugkacikax hlard.
Mujosegey sjulerseor ize ocah yriv heo zukd ja iyboxdo, civib ed kenazw pneapu u cnagaqtm. Hue’wj nevc fi eve velp cwuyixpaaj jbih e rsufoshx’y amoyeav misua ek folgunaguuyimsb uxnoffaci us nzem dai zex’b clap ghi iguxouc vuhae im e sqejajjm uybox obmuv peu’ja evujiasajow rso obfazn.
xuyiagaf mug zo enik ba cimam fuhrufj smu cuheu eg a dgiyuqhx ribibizso azxoj emtol bsi ojjrogge ug nzeotab.
Azlumnaih wfirivxaow eszeg yai wo onr lpuyukdias go o ybigt eazpama aw bpu rbenw yegokivuem, jay unoltfi, uf diu’ha ixehc i fhibm fyeh i rescugg.
Where to go from here?
You saw the basics of properties while learning about classes, and now you’ve seen the more advanced features they have to offer. You’ve already learned a bit about methods in the previous chapters and will learn even more about them in the next one!
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.