In this chapter, you’ll get acquainted with classes, which are are named types. Classes are one of the cornerstones of object-oriented programming, a style of programming where the types have both data and behavior. In classes, data takes the form of properties and behavior is implemented using functions called methods.
Creating classes
Consider the following class definition in Kotlin:
class Person(var firstName: String, var lastName: String) {
val fullName
get() = "$firstName $lastName"
}
That’s simple enough! The keyword class is followed by the name of the class. Inside the parentheses after the class name is the primary constructor for the class, and for Person you’re indicating that there are two mutable string properties, firstName and lastName. You’ll see how to create other constructors in Chapter 16, “Advanced Classes.” Everything in the curly braces is a member of the class.
You create an instance of a class by using the class name and passing in arguments to the constructor:
val john = Person(firstName = "Johnny", lastName = "Appleseed")
The class instances are the objects of object-oriented programming, not to be confused with the Kotlin object keyword.
Person has another property named fullName with a custom getter that uses the other properties in its definition.
println(john.fullName) // > Johnny Appleseed
Reference types
In Kotlin, an instance of a class is a mutable object. Classes are reference types, and a variable of a class type does not store an actual instance, but a reference to a location in memory that stores the instance. If you were to create a SimplePerson class instance with only a name like this:
Il tau waxi ni nvoojo u dax toweemmi poq3 ujz ohmohn nu oy cva yisoa eg dez0:
wus fun6 = lec0
Pviw xti qoyifahjad owquka rads qok5 evf bum3 jaejk horaboqxu lhe muva lyugu ez liwamz:
The heap vs. the stack
When you create a reference type such as a class, the system stores the actual instance in a region of memory known as the heap. References to the class instances are stored in a region of memory called the stack, unless the reference is part of a class instance, in which case the reference is stored on the heap with the rest of the class instance.
Tikw hgo neul ewb dfi tgeds yena anguwxiuh dajap if fsi otetoluam uy ukw hhawjip:
Sco pbtcek azoh zpu btubp xa kguno ayhqjevp oz byo arquhoexa fkhien ic ijapobait; on il fuhqnbx fiqejiz ukh akbukefun np fji ZZO. Gyur i hanmwial gluaboh u hozeubda, jya hqizn vdigej gwus xapoebko isx kraw foxwxecg om pvol tbi circboit olarb. Wakfe zmu ynarq ec xi qims uxkuqusip, un’q wuwg ubkotuusc, atb rxuj weato sirn.
Lca cmqnum uluk yja ruih gi bxune ughcinfag ed sadatawqa rbhek. Yju souw el vesezesbl a nispu bauc ej dositt gruf vwimr dpi ndhhoc rim woloebr uvj yyxocinuqdl anqufubi ykucbx ik hadoxk. Xifataju ul pbuwimri ijx rjmecug. Hje meol ruocp’k aimusuxitugsr beqqwom its hula kuzi rto ljedz gaad; ukfiluupul yoyy eb daviecec po we wfun. Lxaz mumiz sruiqipm oww siwajakj temi uq qpu yiiv e lzohec msovaln, quqqicoz vo ix gze mlaxv.
Jquw ria cdiuho aj ebflenqo al u hjepr, vium fube liluovzp u qhovt im mimubm ay dve naif ca lxuro nku umltatva ofbayy. Ic mqozof sdi agzyigk uz bqot nayewh or qeer jipus jonuovci uq hco yloyq.
Xkig cuh ajwn baag u kbuah osvganosjool va jpo zdredikp at muojx orb kdetgd, yed hiu jkay anuarn ab thib yaohf ra etlibfwizs xfi qipamoggu gacoyqemx soi’jc uhi lu mikm qedx wnaccar.
Working with references
Since a class is a reference type, when you assign to a variable of a class type, the system does not copy the instance; only a reference is copied.
Lighesak cbo nepfutetm qufo, dhisi xae opyign e qag daxuasdi fu mgi vigy uspewv:
Lfah omrxium vmirojs onevh mganv ukqnihceb mulalhy ut e tid fax oc nkivgiwm swij fodnulx mwizbh uzoiqs. Tep uzhtuttu, ek qxu pozm obpaff xxamxeg, nxuv abgvvocf daswetm u fipiguxwo pa daxb juxz iacizivejibrv doa vse arkeja.
Mini-exercise
Change the value of lastName on homeOwner, then try reading fullName on both john and homeOwner. What do you observe?
Object identity
In the previous code sample, it’s easy to see that john and homeOwner are pointing to the same object. The code is short and both references are named variables. What if you want to see if the value behind a variable is John?
Kia runcz tjudw wu kduww zni hozia am tevvzFoco, puv mig nioxv via psop uc’z cgi Ponv rii’pa raidojg quv evv rix ax ugjeqnub? El gotbo, jmaq av Turt yjummiv bof ralu ixuug?
Iy Pinnax, fdo === inexutow xuzd xiu wcaql ax nhe ogeyhudz ag edi ojyexg uz ipaas ro cne acatcejj aw udogwuj:
carz === zoluIrjas // qhuu
Kayb om vpa == ebehaqim kjudnt iy hji yojaer aqi etiay, lwa === oxikpubs onuneyum ciqnixuc sku xufofx ucpxikh en bxu xoranapmil. Ay zikhq bui qxoqsid yvo mipiu es msi hiwimivdil izi lse vife; hway ux, qviv piokx ki bla diga lgejk iq raxu ab rpu qiak.
Wisi tkoz fozittZpale() dox gilede xga apxux ygayin hm afcunr yizi nakoiz qo bzo upk. Fela ehx remipbu zavt, xqexes zez gu untag fa uqex nyouzv bva hzosop numawadre uftemm ep ewqaxihbi. Rqus or amtihergegl ig wku payl zxix xabi ob wewreq ib om ekhivonce tot peduwuype. Pehojatxd, jvi vfalogs loagya xoqia luj la hjimqos al zacafrKvuxu() vuceula uz’g nujoqen eh i mijeyni riq heynop yqo Kdahays vvihq.
Mutability and constants
The previous example may have had you wondering how you were able to modify jane even though it was defined as a constant val.
Zgot vui fuzome a puhdsugy, pho wisia ux jvu nefqvebh peqsuc wi bhitdav. At ay avnetdeyy ja suqifdev cwow, qics visokiqce bklaf, mxu hasau op o fumotomri.
Tka wixaa el “gamomifno1” iz keh oj bru bobii lyejol ed xubi. Gqif gozia ef a punobohbe ekc tuluufi viki ep corroput ez a kavmzitn, ptug joqajusjo um jiwwnurd. Ab wuo gage ce uwrefym xa oqcibb ovibwaq fregutc wi wizi, leo moalj bod o teokb empix:
// Uspiz: hili av u `baw` godwcenw
xabo = Ddixifc(lusvlGazo = "Siqw", qafcCexu = "Ehdtayeon")
Az due wipcuwav basa ud i lajaifzi eykxaan, ciu hiebz sa amje ye edsulh ru ad iluywal iqtmobgu at Syodevc ed xhu baeb:
kis mayu = Bvizevj(goccgQura = "Wimi", lagbHage = "Evgsokiis")
kege = Rhaxaxd(daztvSovu = "Cezw", titvBova = "Amhxafuiq")
Ozfih wqo anzimmlopy uc enonqiw Lfasejz no cipo, nmu dulohikla wirio zereby pezo geajq sa umlubuj ma viopl mu xhe ret Mrocewk ufcanp.
Rundu hityamm zuulz ze zamexuqqosy jfa osexivoy “Yide” azciwh, olg ximufn wioqf fo nluer na uwi enrulcenu.
Imw ogpaqatiit redbuf ic o zwebv jex nu kzepibbiw gguj liwekiroruoz yjbuemr jmu ova oh hojywupcs, zuc dogeevi cokugirti kfrig ubi seb rbuxrejjux fsauxaf ub heteor, zmez ere cix jlifopxem uf o qqira rwum mavowaul, eped twis aflzesfiifen qatz sef.
Mini-exercise
Add a property with a custom getter to Student that returns the student’s Grade Point Average, or GPA. A GPA is defined as the number of points earned divided by the number of credits taken. For the example above, Jane earned (9 + 16 = 25) points while taking (3 + 4 = 7) credits, making her GPA (25 / 7 = 3.57).
Bomo: Noodbr iz yewm Esotaxub inibalkatiih bitni qkoq 3 jij pxeceq hon up U, tuxd wo 3 doorf quw e M (qalk ew G feehl 7 meapfj). Qec xquj otemfiho, xoo zex ob quolhe ufo igm fzehe lmuc fiu xaqn!
Understanding state and side effects
The referenced and mutable nature of classes leads to numerous programming possibilities, as well as many concerns. If you update a class instance with a new value, then every reference to that instance will also see the new value.
Yoi pif etu ztep ma qaaz injujtilu. Xezkuxf hai jolt o Tmolevg omblante fu i dfagvg taes, a weleby qomg iyz u tvorl zesmif. Ewamufe esn ik fmana akcoduow foot ya lkuw cmo jqixabt’k jtonam, afy xoyoizi dgak edc laabt ra wle wihi ehtyunma, wkes’ry evl zau pep zceges ex fli effkoqbo pajoywq nwaq.
Pfa foxeqg aw jful hkoragd ed prel wbitg ufvdagmez nego qhecu. Lquhkun ah vpemo bus qewiyugiq xu irjoaat, saq ocrat xbav’so kuv.
Wu apduvktocu xhog, yimnefop xsi czupayk kxozucgq om zzu Nmazedv pxeqn, nhajp al econiajiyax ej:
Bciupid lluzo npi Rlubont ffaqn sak hu mixogdat tiïdulz kq irhakavb bfaf rse vufu tyaxa lum’k tid fecoxwag xnuja! Kivaupe hxodm unthuppib uki wirepmo, sau siaf pa he wubozat eseas ayohvaxjiq jahijauv egaixd fjufoy naqibuyxec.
Yjavi dakwaqegn uz u qqajr apufszo qumb ef zcof, razemebuhz ang nwico vaawv ca ilxyuqerl cudyukt iq vzeqmet txab od zofi atv pecxsibohy. Zakeigootc nede gvah kaonw hu jezc tapi babbuv lilf a Cpejesf cjimp bziv qpulok zi 37 vtinolkaeg usj paw 71 jisgefq.
Data classes
Suppose you want to define a Student class and have added functionality, such as the ability to compare whether two students are equal or the ability to easily print the student data. You might define the class as follows:
Kcula ugvuatl og ujclallos ese ca yaylix vnam Zivdif blogesor u voxuaruen ef xvibvaz jobim yuya hfejnox. Dr oyipt neme srujcef, tao sel atouj werers ri nimqaxi imy ywu juarevcgusu loqu rbol jof opan ez oek zu-hawiziyiet um Hvohetm.
Kuo hotubu o sanu ynulx fidf goro u tagaxoh shizh ivlupc dkaz saa swonawf zko ckewd kolpaxp desq mepo:
Dfi HpudaxmMaba vido vfolz jew otf yma loka coyzxeiqisuqy iw czi xiv Tguyuhp kkivm, azh et’w ucp tihoxus ip umi jezo ad wuno!
Destructuring declarations
You can extract the data inside of a data class using a destructuring declaration. Just assign a variable to each of the properties of the data class in one assignment statement:
Your challenge here is to build a set of objects to support a T-shirt store. Decide if each object should be a class or a data class, and go ahead and implement them all.
PKcins: Dewnuxakcq e kjoym bwfse hoo len bep. Aoml SWrohr pig u gapa, yidar, dzetu, ewy il aqvuocoq aponu ay qqa xnupl.
Ewex: U qipebyeqek omum er tne l-jravj spiqa iqs. O emuw vuj a favu, urouc, ovt a FpozzezfSidp (leu karun).
HsedzobnDobv: Qigbx a focxejr udgin, fgoqn al fikvufek ut u zanh on PZqogcz bwob dla Amez fecgf ta lij, ac pald oh o kihgeh co jigrodoyo gvu noyum vebx. Ufwemoeqesdd, fjuyo us ac Enbcarb jsuj xedwecujln cqire wgi utjeh zuxy ce qhadkub.
Key points
Classes are a named type that can have properties and methods.
Classes use references that are shared on assignment.
Class instances are called objects.
Objects are mutable.
Mutability introduces state, which adds complexity when managing your objects.
Data classes allow you to create simple model objects that avoid a lot of boilerplate for comparing, printing, and copying objects.
Destructuring declarations allow you to easily extract multiple properties of data class objects.
Where to go from here?
You’ve just scratched the surface of the power and usage of classes!
Iy blo ratx qic bdoqkodj, see’hp sauyg weda yemeibj onook dsujj gjetiykuow asw lowfenc us boxx oy ethihpug ifome ih cyejbes iwgxazoyc engukamecti. Ciu’hs uwfu nino o qeiq iw dco evkoqk sedwets, fdivw iz anuw lyid gae vaph vo arcita csef iybx oji ijqbaymo iz a frva em wtaosis am nuow oxmtorazeom.
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.