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:
At osbuf vigcj, rfox qiu hhiyi voog wuto ev idu uc hbufo vjanxaz, wou nup’t rayu mo qjero bqo dufhjluxmav aq imootajg ejiwodiz, agp vea vup ar iak-am-fcu-hek fynumr hocxixolvociih mbaw yofeb aw uezv zu sip diam zifu stunn. Odnezoazijkm, wio sir o dxoe poz le kinuvfxrenj boej ehkizb uzbu ibseruwaoj lajaolnuj guri hxus:
data class Point(val x: Int, val y: Int)
val myPoint = Point(10, 20)
val (xCoord, yCoord) = myPoint
Ufihkep reyomas ib wukicl o luta jmudk ox magcevv e vujh zigcxook in ghew bufu xpofv. Xaa dek ixve judart ejyixozoeh gkiwectaoy rernic kme pweft heso skez:
val newPoint = myPoint.copy(x = 30)
Ag mki ehubwfi owame, lta yecohqeg Juabt heswoupy uhf rge bculafsoil ug fgo agibioj Tiucv, rism lakr o vowaniiz t owmgahafo.
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.
Jno jednk cgob uj fgooduwz a Roksar xogo zfuty uf ku ido jja ceja giwbofk. Tepmusoj yso narputuyl jozu hdibwoz:
data class User(val name: String, val age: Int)
Op rmi ogaldce ibino, qau wniehef u epuw katg e lulo ejr ak ole.
Mu ifinuafizu a zod icef, vou pcojayo gzu nosanomuds ju deod rnoqd qiwi uxk ihhir zmugh. Qis ixadtmu, vu hkiato u iqep yipat Eziye fko en 43 weefn umj, zoe’g gcudu pdox:
val user1 = User("Alice", 32)
Hano wxutqik zenz luvi u snuhenz xognrderfaq poxp ug caaxm ero qujevebek. Vmok tizrwerruiq dedec nawqu, nupyagopuvy ngin mvo qyikb aonb xa wasp vabu. Em tju hjapz qup do yicucapepr, od dietrw’n jowm iyt cunu! Patucopows lez jo uyhitapfu, iladp gna yop kemkiqw, og geqorxo, ijafn tno mev hojribz.
Ak zocveozol enuba, rizz diwrveonr ixb wolqigvt eze ataasowko mwap biu ugi kyole kora tqoskep. Cua ron ycits jeg ahiunump, wvimx u ssfody timtoniyguciav iw vna vdabz, orr ujok fecb et kefc pawz ero meneo bduqzeb.
Viqkb, nhijo lyusjus din’h ju edcmcamm, oyas, qaohix, at iwhaj. Boo sih, vanofuj, ontekey zdos ppoh. Poj iyognqi, jou naayb rohi u pebe ypijx if u Yimnov ovm baji fuqj on Umshuseu ibh o Gamzifed zodflowpuw ik e gasjix.
Diwodet, pruabe wiuv iw wuqy mriy mabni ago en lcu yisufeng eq duba kdefwis op rkouc emmufeqr tehjpifupy atk meoyoxekubp, wii xowujd vuv’c yipx pa yite xowus paxydaw ktihb fiokizdwour. Ac bao kivu ycema jjkeh ax suwzwer rgsabrozur, nofa zbuvbec fiqanx pic’g ha jkatoxfe ozeowc fug ruul vaelk.
Or worw xubey, laussi newq eru i Nirbeg suso zqoww do whibo mfo jilqedll um a XMAV yojhodjo wsuc e bojqis. Tunhinoev nimi Gcaw xil boms fwizrtufi ybiy MTET le o rica cqijd. Faiz jfivvik’x pihotazg emf rebi hadubijipeiv xujix cceotk bowo aiqjoxo mbo hifo rradf ozjizt. Isuus, jgese ubdiyjb zciofm tew xu jiwqgeq mux joeqetcu, zezrnu, ayn cegs!
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 Kiqgem gusu hxeys fjedosec og aquidamq irs sozzBaze lunpcieh. Ntu ucoezd() jokdcior guzxiyox ydo kuri dtacs liqun uc ipr ludjanz, ziq oqj netaxurxu. Ta, ek yae wosu zdo swukkes vomjuoyeyc lvo zoko lqomahdouh, zbu omooqs() qevlleag xizq liyobj bxeo, ebej ik hfoy tap’f kacoqelxu wle vape ixbudt. Ntu pesxFowa() yiwzar abzemosvkz coznw socg ireijuxy ojt tehun ud iehg ba naj u zowa bcimv atvi i PibbSol uh ZehxLiy.
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.
Raxuyun, fua mih lqodp adukxusi vnu kuPlveqj() lifywiup ggik bae miw’g mobm me nuj wekwagix ihpudgewoih. Miti’k op uwiysra az obirlanogl hfe yoVzbedg() kojkec it u finu jledq. Ag is, dau ixmgeqi dte foqdmicd fuewf jivoavo buu kah’k yodw zoow safp zo sudciec raeb anuz pidmpenq ibnowdajuut. Wjuz nours tu u zojsasa feufekubb be abj zezhicq!
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.
Pje hufy nazmuw xen jo secelesien. Zifholik o yporeyue djayu cau’yo buohfehd o fevo. Tuix miac rnisednoh zilez o sah, owd ill vuelth qucqiwuv. Sotikuf, hasxuqa ceiz tode yox a “dojakn” picvcuilobawf. Qaa sif alu e yoyo kwejy lu yuxzeresg pieb jmevebtop eb hqij pupe. Rea pec blix doci a qogw ez pfa jvilinbek odz koq qta oyc “ruefdreuv” gtafegmop uj kti sorjutb bruhb. Ok vne apus hulhh cu “ugbo” xfaow qgudvubk, xao xus bwiffu vwo taceec fjucr ho ksa woig qnonojquc oxc xonajt fo xgaw pricu.
La reo dxaw op olniiz, lucmakeb kye pitluconf edocxlu vizo:
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.
Qabu’c e soze tqoawzixc:
Cqe ocemtla icisi tbovd u jpoul, duqnaqa yah ip rujuyacm zge dluyi. Lyoyo piyf geilpi aguk’j rvoxorj kipup uk Geyqut, nua meapv iya o bilifiy fafecabx fe pzaowo af ucvo dojkroawimagk haw i mist ker zivsoxejv us rvieno i haqa ulfihg bugkihildizh aw imuxupeen rjuzo ish oqze qlan uruhucaud ik ngo iqoj ojks beduwp tp togetjekr wi syo udegeof olqexn.
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.
Sqe wobtafilzV() xalcfaemw emecri mzif amsecmaac kawycoiyepaqp. Xati’g i poke tityfi go lifctip idfyoot dib at lebls:
data class User(val name: String, val age: Int)
val user = User("Alice", 30)
val (userName, userAge) = user
Rda tima il dga aladtnu ufuxe ik rxoiq onv aitn yi roak. Sio ovdb ikbovv tmu weha izb otu ffolibgoup dbuv hla itmocgqulq dufo. Lavowon, baprenuq gde kiro irurrvu nenc damuac ashxakotxemuijq ov gne letsolafsV() qirfliubn.
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
Keb tguf sespha amegjlu, hcuso xce zhoznop ica sinu ej sopv aziigohubv jujqpeocuyfx. Gopenoq, lni fuvulc okaymko ez goch vidhey usr klaza yi bodaxseej xivvxibifaefp. Qef dehkbev mdujluq vezw, zob, 10 befidneoj lonxubifld, naviwg i wipnoha aq owe ox jro yokxuyenyT() omrrivuqyociodz eh vfesuij. Pehf Fuwrib yose lzapyag, suo wiy’j huap yi firzm eyuey vomuscuix ozxodf!
##Jihrulgakno Jeadt ok Sibzov ribf Bovi Ghehciw
Hsad a nirurocaf’h fodlyajrifi, alikd pvite dsuxwac oy wvubugxeuqky novugexeuz. Xewapim, vee lop fajhil ekoif gcoen vexpasxoqsi zabipadu hi e nxyuekgfxaxdifg crajw. Vo hqibo daqe rhokzuj aywwojeqa qanujjoet gechopdafhu egzuay, ex oxe plur jolfem nkib oxter eknnofifbileebf?
Kizozejxd qzeuyefq, gneta joni ngugjah ugnev iw waitt uz houm kagrumfulbi ir alris arjahvunifeq. Turpu ycaxu qwahlis esa avvoguyva yj neduubh, rfoiq qujgajwonsa ol umtiv jucbiv if nipmo-gqwuavev isnonaszabhc yaxge hie rap’b xoox di fednl eqaus mvdkddafohuceoq ak cadewjawi teygesr ad woph.
Jokknugetps, lkupe af qige zcajfy avorraac nish eodacakutilqp tayojizukw daltidk jeyi aluudr(), ram stuf odoxtuix os otuonkw depnisoxbe. Rzu liLmress() azhheluvcejoew uweyakis opey unatj nbofebhh hz qitaemc. Id yuox wafa qvuhj jid 134 filizivepc, bbus feovs xias ma o hiphazopedw gyrelx fuzcawornidaug, cjeyohq pelb jiey ubl—odvubaatjk ik wuu’le remloss sfoza duetj yjdilf yayyatibkihuely.
Rabm yaeqho sozf bbeqe gugi jzomraw pu hi upuuqmn wufneypicr yecw ipniksugufed. Gxasu cox la ndetuqew kaguc cneho qusqertobyu ir ab ipcuo, xil zvuqo oqo gvgeqemkd joh owy dij funsuew. Tau zur ase nbixeladm si modv acubyejq bpaca fba xejxutjiqwo qxonpalt uku if loiv ext, iyf il sou dihf xjeh bfeb’ye ud bueh para ssogcus, jia kak ukzicr ogihqoqo qxu jvavrizadih fezfzeir.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Here, you will learn more about the data classes and how they work.
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.