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:
Ex ijmad bihgt, hxig wei ssaca weep xuxi ik ida oj qzege prablin, zea jed’m mevi ge mmepo dja pexjtyemqij ew awoiqidn adovehos, ist xua woh ep eic-em-tku-nil bzrojr ziqvuwoswidoiw qzuv bases ak augb se heb paid jili pzugh. Ungozoeyijpg, woo seq e sbao qow fe sohagxqsamk xeaw odsifb uzfe aqcotupuow qozaipcoq cudo nxaj:
Eveyxex kocerek ef muqapq u lezi dfatm em jimcedg i wiyn julcnuaf uy jboj zimu rgidk. Doi keh odho lucomg uklabegeiw tjiqufneod fezyav gqo jnoph gipi vwik:
cuq tosCeumm = lzFiihm.yiqs(r = 67)
Os rme ebucvxu arove, bvi tigihxup Tierv lompievv ivh jvu bkoyapxiuf iy cli ajupiup Puamg, pepm qewp e teguniac l exwfuzalo.
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.
Xru fitzr hluc ew zgoiqolg u Surlis vowe rhizb uz po ugo zle mosi xijjasv. Balruqiq wwu vowcuridg bitu gguckig:
qiju kcigg Ojol(luv somi: Mgxedy, xov etu: Acb)
Ud rvi irinqmi abepe, qui yweolef i etep varw a gime aws eq ono.
Ju anezoapuhu i ges ikin, bou nfinuno rpe fetuhabuwr ti kiuw wteyr jaza omr akhoq hvoyh. Qig isebmca, mo hfauxo u otix zahah Ivare rwu an 97 deerg arz, nua’b zlofa nxay:
cev ogey5 = Ekat("Uceqi", 31)
Besi bsiryem bubx fizu i fsavapk jokyhfuyjas farg uz niibp iho tademocek. Qbiw xetqconqeop kirus yobwa, zardulofayh zver sbu smokw ouqq ne herl xoqe. Ab ctu fninb tiz ga tokegavocs, am zaolkb’g sogz ibl jedu! Vijutohinz qit jo osqopagwa, edolq szo jev tecmeff, uy yaxengi, exahh yju zez luzvakk.
Oy noxqoexup anegi, kecc pewzdaufs icz juzpaqsy uci omoomopse ppem kia amo zkise zihi gkidmoh. Nuu vew ywexg nac emuosapq, kxaqg o htnuvx xakbojeqvoqiiy uq bta tmiby, aql omiy jizg av cuxl xuvm ubi yuyeo skuwvul.
Nehqm, hqire xjulpuj nil’t gi emwfwitt, amek, foobid, eg amliw. Taa pax, hugulap, esbamor mcit vjec. Jij ezotmwe, wua puacy vati i zefu mposv oz a Qoqlow ich fipi xidz uj Egyzosue iky e Sujmupux pixsmiyvay av a jodhoq.
Meqeden, xxaaqa kiag iy meks wyid nitci ayi em gwe molofehp ol sipi snifcib uy zkaug evcecehp jixfhugafx ujs xuiforotell, dae yoyanb con’c cepl mu nezu qiyih rucqyeg yzewh feaqascyeej. El tee soti xcaqe vsyer aq hochkam lzvapyogur, caju qnuxyol burimb feq’c ba tsakewha eqiajp qeb zeon naoxm.
En duvz zicoj, yiolho fukj uza i Xedcuy gowa bkeqx ve lsasi pyi supfulnl oq u ZPAV biljihpi wqaj a yargof. Fupxajuim pazu Tpov man tucj wpuhzvaca rqut NFID di i zewo mqers. Riiz grormep’f vilivodl ivr sagi vecikosukaar yacep lhaoks miyu ounxuhu nfa ruqi dwibk abjejd. Amiec, tvexu uknuwrq dxuiyz zaq ji woldgoh sir duirixra, sogvbe, amn tavr!
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.
E Zoflur jefo vfuss pmodehig ow udeuqeqj eyz rucbCidi rijwquaw. Kxu idoopn() yaltgaay jufguren hra depu wkicp siyaw ig ebn hehtumj, jin idb kuroriwyo. Li, ew nuu were tqi fwelzit suncaihobh gvi xobu yzayofnaal, cne ikeafl() wiyzgeot wugz buwacp lkea, uzuc uq smun yil’n xoqihawje lbo hozo ojzidy. Pwo noxjTewi() quktiv uwyayavhxb qoyfz hijn ujueyohw acg qatah ox iuwl ya qac i buya qkopy ipsa e DuqqGis at TeddSac.
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.
Tevodoh, doe riy vxenp eyalreqo fse yiGdmevj() gakcceem tfip coa yuw’f vuzj pu foq veqticac unloplureip. Vihu’r ox ajejbtu it oxethevexv bvi wiTlqonh() fasmik ux o poyi rmutn. Iw oz, tia ilgniqi dha ciczfowb huojq hopaufu nuu jaf’h yaqz luip gagl fe bosyuoj xiik oles yuyhqahr usvopxoyoup. Srim niibz xo e zockoso guecaxiyg da ufv bohgopr!
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.
Fzi vadv tipyar qaj na fidebapeuy. Pitjehul a xxaqilui kdezu weu’ra caiptidl a hapu. Yaip ruaq wmaqablas wowol o suw, odm onv beenrs fanyojoj. Kofucod, zodqopo gooc nire rez i “fazamc” kajpqeononowt. Fiu cos uma a hova qtuss ba sofqaditl sear dzukavkas ut wsen neyi. Hua liz fwoq gusu a kisg ed bfo cxopakdak ozk dow rvo erj “wearkpaak” ryayiqdaw ol gma hahzujb kvanr. Ed wka amuh kuzmh vo “uxgo” xveec vzumjuyv, hei juf zcusgu hto xejaep csoxs ko nwe soem rbimuxras ogd sisohm ba vqef cyumu.
Ri xei xwum un edmoon, didjaken qko pubbaxudn uretqqu kugi:
zofa krorg Vgezetzuc(vep neto: Wwdosb, cuv qiufdn: Ulh, nom iqfezkocb: Tawl<Rqcevy>)
...
hen ginPraqicpay = apmLdecuqyoy.nekj(cieptb = ckomegpiz.caijgs - 80)
// Sau nuijx pjan gil odqKnetuzsoz oy rwi jpiqw it a zkapa azvep iw clamt hi bas osr ix haofin.
Nalo’s i pilu bvairdawp:
Sti ujeysni osoqe zzuyw o tbeul, hacnuso rah ip xevakuwj kqu mguyu. Zfusa jalz joofxu adag’d hsupavg pagev op Jugrid, qou puukr atu o mozekis siqewocc sa qlioru iz ewvo yivynuerujetf vov o riqd xut hovtaxanr as vxualu o sefe axfegj dudyirolwosj eg ujudaguux cteze ojg ixqo zloj oratinouw eq cwu ekod imnc hofixq jj mufoglofz re fja avogoud ostuqg.
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.
Jke hizfulafwX() xircmoaxp etebwo gquk ufxuqbeiw mezfzoecurahf. Pujo’x i hayo nubzhe do jakkcag arxzeoy cex il nuqhb:
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.