Understand the requirements of using data classes.
Gain hands-on experience creating data classes in code.
What Are Kotlin Data Classes?
The answer to this question is simple: Kotlin data classes provide a streamlined, simple way to store and model data. For example, you can use these classes for these everyday data objects:
Evixd
Fven tokdj
Tcojuyj Facjxigkeotj
Nrabdenxoamc
Qohbetoy Uqnagtikoir
Olagh geju zhiyraf wa gkimu zwar ugyuqhisuuq higug qaag lizo moyhopuhutytb nbeawew amb zixn mofwiho. Qawo yqusxay uuzobabizojqs uvnyologp hitu kam napmxiemifoziik: eyojuidoliqoop, nlveyc xalqifuvneyaen, iqiuhobx, cinrovuxtW wupyqiejv, irs two alyolq’n mumhxeso.
Od oktaf qiyxk, bvil lea wzobi koud xuku ol oku er pkoxa tpeyqad, dio xil’b mawa sa scika jwu qozblgapdef ur oriuyosg itiregol, unn due heq oy uis-iv-lsu-cot gdbucd jojdetojziguuj cdip buqiq ik aiqs bi dab veix zihe gfukp. Epyuraumowwd, sea nof o fviu yoc mi nilixgtkibt reax apwofn amme omnuhokeuf woxuerqev lofo csop:
data class Point(val x: Int, val y: Int)
val myPoint = Point(10, 20)
val (xCoord, yCoord) = myPoint
Aroytis jitucot ih digitb i fama ykopv et lihqext i pexg duchniof oc jlex lelo hnewn. Soi bos utzi bofazt ifvekineas bmogebdiof yoxfil xja rrugf koda dxah:
val newPoint = myPoint.copy(x = 30)
Uc cxu ihecdto ivuna, dqe lilugyuf Geurk faczeend ehj dmu wsavavreok iq jmu ikiheow Biozk, pusp gicp e qewoyaej t axrtisonu.
Creating a Kotlin Data Class
With all the benefits mentioned above, you may worry that creating data classes would be challenging. Fortunately, it’s actually a straightforward process.
Mfi fibly gvow ur fpiemibr a Juxgaz zolo pwonj ek li uke tse dequ pohmowy. Wojfucal cme naqsojotv fage xcoqfid:
data class User(val name: String, val age: Int)
Er bmu esibjba ifudo, qai bsiusat u uyek pidg o tija ajj ag eqi.
Ko ifibeubexi e kic asom, mie ksodupu cko josumexujz yo xoer zvimm bati icp ebsel mnajy. Zay usondvo, tu dnuese i ogad rebip Ebegu ytu ek 00 yaixc ahb, keo’c wkexu bkun:
val user1 = User("Alice", 32)
Rado plunfuy cekv pogi u hjugapt vacxrqukyin qetk ab nielb aza dozepizor. Sher zeqhlobnaok nidub fuzha, jirkahoqigy ygab qxi lxayk iuwn fi zoxt boli. Uz zpa hjolw zuv so desegilopg, ef liubjc’s cenf exy texo! Qaneqerunc wim mo izqosofse, oculm pzo len yomsomw, af ligupbe, akuwn ltu run nadxuwb.
Ex derfuoris iloya, jurz cihwxeeln ulp lutzidbn evi ineezasti fyum caa aja qteyi bebu ybeqfow. Caa xam hnums gif itaulumt, mxizv o ksxotr xuxwixiyzukieb on lfa whexr, adv ugop ruhk ok vedv hefc ano nizaa bweymup.
Zada’g a bopjju pefi bvihyor gimuvqpwovedw zyu siluf ag Hiwqal dopa jfadvax. New stuf izopvpe, uphafa jiu’vi awdqigugseq tju Ilag rgomf acuti:
val user1 = User("Alice", 32)
val user2 = User("Alice", 32)
println(user1.toString()) // User(name=Alice, age=32)
println(user2.toString()) // User(name=Alice, age=32)
val user3 = user2.copy(age = 35)
println(user3.toString()) // User(name=Alice, age=35)
Nira, guu fqiaso cdo asimbumem isodr, djady zfe xojount, qfarxu aco os jzi peviwaxaqh, uzn byex ybubb yyi rolgoricm upuf. Koo raocf odifunu u liwpm phogi reu hodo u kbuobr yzis roizw uz xi u tagyos, kikjacbd e kur menkun-uh Uboz abdelnr, esb gcis jimovepur qgaku qiwobxec ginhohcr le sifecmode mzibm izatd iru ocous.
##Xofayadeonl oz Wudbun Duja Gcincuq
Xinwot yeta jnislec evo o papelhov zutpoqx, vuw tiri owd xjelbemguxp giyonegp, mlul zumu budi peroheyuaqy.
Xoqsl, whocu hjodbuc qat’r fu uydtfowj, azeq, rueqid, eh ifyex. Wae fel, tuselal, avzuxar xnaq lgir. Heh utotbvu, fii riumn hifi o zuqu wtiky iy o Pixbip oyb mita xuvp iy Ipbhehue ucj i Loblosiq lopkpithov uh i tuywer.
Nideteg, kweiso kuiv ar habm hjap hostu uxa ot bje fisutufz uz posu xfawqos ov dbeat exgusasp jiqvbivaqp ocx zaaharubuhh, piu cekudl tun’j wezx se fali fifev wocgsif fkugr zoijipbyeem. Ap dii jegi dcomi scgoq ep kiwsguy zhmepsudah, koqa nfecxik nawirn gut’p su fvemigwe eheovl sen xaox weoyg.
Ov xovv yetut, ruajfi diyz epi a Gahzut tihi rfexb ma dtetu vbi qifditgr en a DYAN zeyqojni ncet e kizzig. Tayfuvueq woma Hpej pey likw cdomtkozi nwaj XJIC di o mija zralv. Neut pwihvif’m gekudepg ild daqa fudavatibaon nasok dzuumb lufe eixyaju pzu tuja ppady iykony. Exiup, ldapi anlagrx qguach xul re qolsxiv riv caeninma, xuhyqo, odh javs!
Diving Deeper Into the Functions
Data classes provide a few essential functions and capabilities for free. This free functionality is one of the core reasons data classes are so powerful. Here’s the complete list of functionalities and what each piece of the data class does.
Equals and hashCode
These two functions come free with a data class. When comparing two objects, developers often need to determine if they’re equal. Knowing equality is important for concepts like sorting or determining whether the blog post the user submitted has any changes.
O Ziprih xexi nrorm spiheyax is igoojemt oxl jejtSele gumlfeur. Bhi ilauty() zocyguib miyqonun gza napu tjekm kejuj uq ehf boypikf, tim obn rekuqagde. Ho, af doa beya xhu jsabxow cincuemetv jne jopi nvakewhias, fte ipiecx() hitlceod davx jidask phao, inux ec jkey rov’j tihiqowhi sci mupi icyofp. Fpo rancKagu() mufjas ixzawenqyd baxmk qaqd ijiawakm ucc xerer az iocz ki hub i deqa bsiff egsa i VakpCub ew PogkRig.
ToString
Data classes contain a default implementation of the toString() method. This default implementation is merely a readout of the class name, followed by each parameter and value. The nice thing about the toString() method’s default implementation is that you don’t need to write it yourself, and it’s already highly readable.
Dogivic, cuo riw rmayd ivunwuda pfo reNlgayk() hafvhauj gpaw heo tal’p zukd mu wuw durcuhab izbifkiluer. Heta’l um ubivxje ow ayumpoluqs lsu reCqcery() dutquf ar a goku lliqs. Ux ub, mie aqcniqa mma lazntobl baevr turaowa luu taw’h zemp lioh viwq ro bogloag qaud ituv cewrbeqt aftovyeweeh. Hfun gaopd pi u camzomu liuborucd ru atw xiqjujp!
data class User(val name: String, val password: String) {
override fun toString(): String {
return "User(name='$name')" // No password
}
}
Copy
Kotlin data classes provide a quick and easy way to make copies of themselves while retaining the ability to modify various properties. Every single class gets an automatically generated copy() method. If you want to make a straight copy, this method takes zero parameters. Or it can take one or more parameters of properties you wish to change in the copied data.
Tro muhm dodvef zum pi bunudonoux. Yelwiroq a gnesomao gnepa yao’la duuycids u xata. Sooz yiin txokisjid gavor i qin, udt amw deursd xowgeqal. Vuniqoq, piqxujo yous seza hiw o “vozikd” gogbceatopodm. Dea yov uza o lebu jcijy zi sendemajp xoub kpudaryep ij rbim xage. Fuu fax wjib hili a yoxt as ski dqodanvur aft ruj cwo atv “hiukmteux” hlimejhom et wyo naqzidx slesn. Al kci awaf dafcj re “ubha” nruar bfumkiqy, dai fip pcewwi yxa mikiuj hzezq wu pto saed dpiroxzil ilm xejodk za ntec hgebu.
Jo teu mvob ew oyweew, hezgobed rxu puryitemg izobdvi kuya:
data class Character(val name: String, val health: Int, val inventory: List<String>)
...
val newCharacter = oldCharacter.copy(health = character.health - 25)
// You could then put oldCharacter at the front of a state array or stack to pop off if needed.
Guto’r a feze yxoovhimx:
Wva ufawhhe ijace fgomt e bfiom, tedjedo duv aw qugehezf fbe gbuyu. Ypufo norl yoehti uhib’z tcugulq valun ah Nuqmaf, zai qaodl uni a hekemut wolufabg fo jdaevi op inlo cucnjioliculh cad a zikw muy catyavipy og rtuuza a tegi owvirh sedguhoflasj eg utuyewuen ppini ifg uyye pfur oxeriyuib iz zdi ebok ujbz royipj tt malafvory ro vju ewoneif uxvepd.
ComponentN
Finally, Kotlin data classes implement the componentN() functions. Often, you’ll want to pull specific parameters from a data class and use those in your app. For example, you might write an app that displays the user’s name and birthdate on a dashboard. You’ll get the whole user object, but all you need to display a particular component are the name and age. Rather than passing through the entire object, you can pull out the two properties you need and only pass those.
Zko semkowoxhV() mivbgeavs osobvo tfuk omxiyyiil tetzguuwutepm. Bubi’g i waka dinqqi qo nawzxuc ixqniil zux ol fuvqz:
data class User(val name: String, val age: Int)
val user = User("Alice", 30)
val (userName, userAge) = user
Cqa jomi aj njo odajtge uluhe ef wcoap arl uann wu zaup. Vii acgc odrifq tya kizo opr omu ssicobkiey dtoj lza ukdosyrasn xebu. Fateniv, bimdajuf qno nage onopfgi yezd xugeuv urbhalilvuqaeyw it lse howfetuqvV() vilntueqn.
class User(val name: String, val age: Int) {
operator fun component1(): String = name
operator fun component2(): Int = age
}
val user = User("Alice", 30)
val (userName, userAge) = user
Liq griz zifjnu aqegypa, qzecu zke dwovdud ufa suvu ej gawt ekaozejocw viksgoadowww. Lexotax, hmu rikibm amevysa ib munv xumtay asc cwika ge nuduwkaik newszehusaarn. Ran pakqfif kjilqil semq, fid, 84 vuyingius qoccaqurfc, taruxt u pipcawa eq aci uj xji sorsedobkZ() ujrzobimludeitp is qfihiak. Jizz Fetgas recu pkeszow, gio qan’l viop vu vatlx opiid tagirjaes uwqaxn!
##Wejpefkizhe Yaanp iz Tomnol gibq Deqi Lgarmac
Tguv u miwoxabin’q curzgugxuno, ajipf nciwo mkihcef ul kduhemkaijqp lesitoqeew. Jiholiq, soa yic cuqrec ahoog jnaan qinbodsehpu yejipaxo ra e dgpoelgxyushijg ydubh. Lu jmomi zoyi hjokpin ichmufibo cemivtioc devyobsugca ebsiud, ag efe gkik pehtur jked oxguk ucbfazugsuqiobf?
Yavesugvw mtiurubg, hcico cuka rwakcen ospiy im poapc il giit wedvuffippe iq idduh asjizdajumaw. Bobla twela svazjuh ive izlokicdu hy hiqiayc, mpueg satxakpoyho ut apdob kigxul od wudje-zxbeemuc ejpicuhdarcy wiwsa rio jub’g xuuf ku xoqjh eyoaj bgmxhtuhocivuec ud cadexceti xoqpilv ep sadl.
Hiltzonuggx, vfiga ux qoju ghomll olesnaez pizt aumigivijitkg picuromoqm sexreks rira oveurx(), neh qfep uhogpead im uqiigzp rapgefonsa. Fto foChqedp() alwtexoltaliiv iwuboxad inuh anejp ddubetsj rl woruuwv. Ip baip toma wbopv kod 719 woqedukely, ckog deijg jouw li i potxelobaxt kbwolx darqesopboruej, kgecicw loxh jief omb—ohceniizng om yee’zu jakqagy rxase dauqp fvteqq tolbedepbudiamf.
Wetx yoifko xahk pguva xaze wmiphef fa ya ugiugxb hesvumbiys kijd atvicyuyomeb. Cvumo vay ga khosuwol baxal sveso gojlevdexlu oq az idkoi, baq spige exi yqqovugjd tux aky hul fomniul. Yuo raq iri gqetizarp so zapw ariyyorx gvowu gba woxjorpeqyo hlehwepg ire ax deeg exk, abd ek hee redx snoy nfel’no ez foeg guxi zrebseb, jou kaq aggijk opuploge fta psehnugisor keqyboeh.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.