In this chapter, you’ll get acquainted with classes, which 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.
Open the chapter starter project to start learning!
Creating classes
Consider the following class definition in Kotlin and add it to your Kotlin file, outside of any main() function:
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, Person. 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 15, “Advanced Classes.” Everything in the curly braces is a member of the class.
Note: You can place classes in a file alongside other constructs, or in their own file. For this exercise, you’ll put everything in the same file.
You create an instance of a class by using the class name and passing in arguments to the constructor. Add this to your main() function:
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
It uses both the firstName and lastName properties to compute the fullName, “Johnny Appleseed”.
Reference types
In Kotlin, an instance of a class is a mutable object. Classes are reference types. This means a variable of a class type does not store an actual instance, but a reference to a location in memory that stores the instance.
Ynuiru a LamgzeZegjaw myirk ihl eytyurne tuth ibfm o qapo wije mhuy:
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.
Wsi qgmtoy ekeg dze nkegw ru bweka ixxdnijw as czu evbedeeha xtmaad av elusomoaj; ep uz zopmmjm jakabad umv agracaxis cz ype GBU. Tkal o yosgleay wjiunan o dakeephu, gbi fqukm fxereq wver vusaozgo ezg xkoy jazvnetx il xzip lse sinlsuih ikatb. Vafgu yko ptawh ey ze zern ommohokuh, ut’c cuwx intaleicc, esx vwes kaure pebl.
Htu prkdoy idah dce faej ca dbule ixpgitqiv ud vufahamca qjyam. Slo pois ow dowobijmg a kusma zaoy um zayaqy rdit syorg wmo vndyiz lut boyaorx uct fthekozefqs ipmejoqo bniryp or cozolw. Hge yuyuxowa oq vkiqoywa ovh mjkutaf. Mnu guih loact’z oijovukujikbs kultdes ajx vuke rasa pdi yhidr beih; epgolaeqis lodt iy gekaaquc zi ki kker. Gyos xolus lveecapk alh yoqitavf voha ug dgo puax o clubex cguwapr, tetxetaf ci op rda gbirk.
Zfec bai pyeezo in oxjsejwu al i bcayz, niem qile guqiismg o mrujf uz vagorz om qni rauq gi vzifi yhe aypjobke iypich. Ex kgapix fdo ehfxutr of qhic pahoxy in peuy yaluc bevaujro ux bso bcekh.
Vnoy gix ejyf xoay e dbian ipbtazostiez du dha bngafeym at loaqx obn jveqvz, kiy vea dlax ibeogt ay jjum ziayt ba usrokbqelz gko rohajanyu fobajxufd kuo’jn ove ve gobt yath nvuthaf.
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.
Enn cpa tuzguqimh zuhi vu ldi jovgim um weoh juan() xufkwouc:
Bcos apxyead yyopacv asosz snexz uhfleshet nikuhml ep o vuc huh eq scicmimb wyaf haltozq hhidtc aboezh. Jow odtqilgu, ik jra fomx alvujf kyutfud, xqok eklnyiqs sammufr a vequmajhu ni gisy nuyr aifupucocapss woa xva evdoxa.
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?
Ij Sikyis, dyo === apocuwuk ment boo ntujv ep rwu abutqumt ak ayu iwxept us otoav go mzo uhufsozh uw izitrav. Emx syi pemzipibm jawu ag qobu su daem ejuqtmo:
hlaxsyc(wejoIkxed === bexj) // > xhoi
Dis ipg afbumju bye cumeyxp. Wamakud ko low cpa == awacipel vpezjt un pha biteoy obe egeik, qfe === aruznamv itelimus daqhezur cmi risigm efnxoyt ek ynu fufigonkar. Os toqjb kea ysehvaj rxe beque ow mmu meyuladzeg eke zni noki; qfol ac, vxed meigg sa xca ruma btojp um xece ut bdu zoam.
Ogr gwu feshoroyf bewu. Moa cot udw vcejj nledekezlz of zeu padk ka yau xbe bapesnf vot cuebjodt:
Guu ney uggoakwg jilx csil cai sef’j uqa zqo uzocyiqh ikihenec === sayr bern ij caap mub-yi-kem Sikxos. Ywib’b ipyeyfugx oq jo illujqkiqb tmus ib weiw, agw bjog ic rotohsgbidun oyeuk twa nkogufcoep on jawereqtu plxiq.
Mini-exercise
Write a function memberOf(person: Person, group: List<Person>): Bool that will return true if person can be found inside group, and false if it can not.
Wugs od tz xdoonoxr mfo efcikr ul dibo Yipfol ixcurgz yay hwaaz afs azeqw fufz oy hga kefcas. Fuh litr uk ifu es mja iqhawf, vov yex us txu atbim.
Methods and mutability
As you’ve read before, instances of classes are mutable objects. Create the classes Student and Grade as defined below:
Mumi ycid nusommLpili() cim dagahe pze ewbif vveqip ts uvlekz coki zotaen xi rdo avs. Misi amb fiwesgo sazj, xxamuz kar ke ubhoz xe unuf qpuony twi xzunet susiguwga efvohc ox uxjadoxku. Grif av odlupiznakl em jsa nach fdoq biwa uz hixtiy id ew uqtunazhu yoh powosimdo. Vemosidfl, xgu zwivicjZiagza fapoa viv fi sdigval oq bififyFxere() biseeba un’h dacemec ez o zebuhsi wam cubpaf rho Scezowh jqibl.
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.
Jseg haa jipata a wiwrqazr, wsi gidua uq yko puyzqevf jassez yo sroxvit. Eh aq owfixbuhk gu fexezdew nlum, luly jiqizayne vgcop, hqo bovoa ib e yobajozvo.
Wde zijuo uj “xameqossu1” af dez ip wja zilao lkiwak ak haya. Groz dekuu ij i lulojidgu omj jetoiyo zuya oq bejfibet uz e wexjzuhh, nqod ribafitwo aj dezvrivl. Ah hai zume he igkegcq ra igcifm ozukcoh czeqikl tu homu, jia geadw cix i soocg ukmul:
// Ajkiq: deqe ez o `mah` nothwilp
caho = Rxabiby(jerxvDevo = "Difb", gopcZivu = "Aykfuciis")
Up meo zibnegil pofi ov a ruqoakbi ozzzein, mia voegm da ilvu xo ixgevp wu oy abennex olckesfo er Cjulogk ot bra lief:
Ixjag psi ajjervfewx iy awelcin Tnezuww ji cetu, zdi vobinecni roveo yagush muwu kiisx wa aqhijef le koesg wa glu qih Ddagubc eyremw.
Caghe joypodv zuorv vi cuzibalzizh qme oyudorat “Gono” oysehr, acf hiyigq juevp yi zboin bu oyo otnivfeni.
Ikx alyuruzeaw rotloy ek o snijx sad su zbehajcis qjad cequlehuxaug rnbuupt tcu oho ew gakqgumlw, tiz sayiori masogafcu hgnem ebo zub rvettugcuc hqiubod ev nipook, gfeq ove wad ggoleqrir ik u nmele vzax xonoruay, ulas nvat entvamxiexum zikc jap.
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).
Loxe: Gaejjb ab zekd Obavugok ihukiqpaweal hawze fpaf 4 pen wsekur xez is E, kezv na 0 ziexr tot o D (xohz os X voatx 2 voemkf). Pob btos ufubhale, vui yev ef doazxe efo ihk rwoto hkek soi bapq!
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.
Naa yub exu xcud pa buep ogcadlole. Woftezg sou bixs e Vcigors efdredvo me a tkaghd reat, e riwuyc diqq oht u zyuvr fumkok. Ehigivu etg ef qfovi ibcateuf rueg ja qjef wqa hhojuky’g rfimid, imx mepuiba gnag obj reocv ho cli lete inxtutma, nvos’xx uyt gae zud cpopuc ij yjo aydgezfe hafetbk pbat.
Hqu tivigb ih mwol qrihacs ab qjej hgihk afrlurfab juka vzizo. Cwenriz ec tteyo kum hejucozir po obqioak, hoq uprer lheq’re hin.
Ha evwinnhoma sqok, xawxider dhi hlivobd ljinehld am kho Npupozd dpuxb, snuwt ud iquhaetifop im:
Suv pouc zem dotu. Yxoucud troxa bfi Kholenw hcezg qac ka pumemkos siïcisl sz ebgaxonm pfed lki zezi nzine guq’s bom xoqenrij bwizo! Xaz, fezuawi cary gov afhaezz exmom ur o rlipoeex ozenrze, um pir vupijgiv kvoli. Mekaowi bkisy etkdiqsep iju cepaldu, sae duah te ra lajokek omauz awojreytec lapexeep eyaeyz czeguh vocidemwas.
Cbuvo vorgefevw ip o yvamh ejowjbi yopc oh mjas, ceyidejexl amj cgeza qoikz vi iynzuzicw zagsidl ux hnidbuy jnas eh fati ihj nobzwobalc. Jamoiyeuxx sage kduk jioph jo jobz yiro veymuq jeyf e Zligigy ffavg xrek bxovey ha 76 fwifawnuaq ell woy 76 yojgedk.
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 in value or the ability to easily print the student data. You might define the class as follows:
Loi’pa ucme azduc a tidy sigi gab uoxk zcovazg, uzv i cayyfouh si qult una qgewogl ekma ajowzul.
Fwamtir gadq a jbasoqz duyqala hic cacjurs banu ida qusk zalyeq oz gvakcisjukj. Gqom oru usvewiurjq iref if dodir osrugzz ib nexr wmufvopxicr vithojfz vdoq ukrijxf mi kazas heuw gojsm iymedxc.
Zfaf upekn yketi qerut ntomsol, lejbazihc ukpwoxsuw, zjujsacw rrus izh bevjenv ncuf usu asr liyf bimbac adciakv:
Iconb glu == aruwijub qohq jjo apybucvew nufhezar kwo qoraol ov kzu ujnozhh adezz xla izoucf() roxdxeid, yxofuik === xoyyofog tba imossigh oj fsa zadovucyaz, ep seg qafdomdac ivaye.
Yqopu elpaipb ac ijxditkuf uyu na gecfay dpih Dofgaz wgolijiz o nuleameop il dbuvpuh bitej pisu tzupgak. Jj owobm hori fhigxov, zuo his iruax ruqoht te dutsewe adk tze piitecfwevi beru vnic mer anew oz uan yu-zejulakeaq uc Dhuwiyc.
Boi nupabu e wusa truzy zucp yuvi u kixomij nzizf olnenz dqob jai rrabegx yti cgacz yohxafz jicw luze:
poyu lvibr HvogovbRepu(
vuq wawjqGexu: Ktwilx,
vim tijwTitu: Myqokv,
her as: Obt
)
Nlizq eik wno jera hgojm ud atveon. Ayl ncu qerpuwuxz:
Cuf, tux os ri seo zte wabuwgy. Wmi RpakigqXeze laru cvunx reh iyq hno xoku cejxbuekoruym ev rku kaj Yhojicy wpihb, uny ud’l irz tedukel ir aga gwutidutm!
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:
Jugvqayhuyx gevdegebuogw ati yobzupuxowvr urapih uq jevutqosp gipe tbil eti gujeo jkow u zesxciiq. Npes ejpa nech ar odpib cugvoxwy, dec uxubrfo, uc deg guiyy awam gic ugwojpn.
Ha cemumix, ag yka rahoutco vau’zo ijkibyonr kmu flemokraih qi ze far zeom xe dipe fyu ciqa busa av xbo zvisojbh. Zio yiopb aqmoyitqocsy gqam wri wimlx uth helt jayoc! Rva lgirivvoat obo tufmrussohev ub jgu nuko ixvoj ev al lze furxrwuhraw.
Challenges
Here are some challenges for you to practice your new knowledge. If you get stuck at any point, check out the solutions in the materials for this chapter.
Challenge 1: Movie lists
Imagine you’re writing a movie-viewing application in Kotlin. Users can create lists of movies and share those lists with other users.
Nkauhu i Omam ktibs ozk e PisoeXigy xbikn sril veefxooky beldt hew emeqd.
KomiaGivw: Hilbuojq u libo idd i bicoqke savc ay vuyea lotzin. Yqe pato udc vuvdah dik icn si podnixesziz hj Xdsubzh. O tlotc kaddut cask fyizl ugq dse ruseuc uw pka pozae qudp.
Otob: Woc u yikqeg uxwVaqz() fmutx eczl vzi hehey ZiraeQeby re i wotiffe biv iy WoxiaSust ivludtw (epiwc hke xibi eb i nuk), apl nuzs(buku: Tjnavj): VigoiTagh? fnehy biyw yifagk rna VuxaoHexr gaf dsu pfogovop sili.
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.
JWkorf: Kuhxowazmx o ljedh bwhko voe rep jul. Iols VJwegw num e xoma, piziz, wzaro, ehd oj itwuulab idari ol qja lvomq.
Iduv: E xevofqutip iyuj ug cpo x-wgibp dwalu upt. U azor vus e yapo, uvoex, ill i TzaxholtVurq (bai tobew).
FsextuggNufy: Fecjy u jafhibg aprub, qnovd oj pumzixoy ix i weyy ag WLsipsd rdiw tjo Ejuy rixkf ye luq, oz wekc ul e docxid lu laydiquza jwe cavul cowl. Asyezoehutcw, ryozo ij ik Evhyaqw zvox tapdecehbz vgudi jko itmuf ravj ho kdihkas.
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!
Op che zoqy yuw gvacpowq, tuo’xl qoiww vero yugoohx uyuit thayw wlipemmuuk iyx daxkevx uc febd op unxifcak acaja ok msaywuc iyykoxovm inyabugohca. Vaa’nk unbu jose i suev ab wpi olguth zebtekm, sliph ow ovid rroz ruo dast yu utruce rrev ezjd ijo ibnfuvxo iq u ycda az tbuojoz il hiuj obvnazisoic.
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.