Any technology that aims to provide a solution for multiplatform development attacks the problem of handling platform differences from a new angle.
When you write a program in a high-level language such as C or Java, you have to compile it to run on a platform like Windows or Linux. It would be wonderful if compilers could take the same code and produce formats that different platforms can understand. However, this is easier said than done.
Kotlin Multiplatform takes this concept and promises to run essentially the same high-level code on multiple platforms — like JVM, JS or native platforms such as iOS directly.
Unlike Java, KMP doesn’t depend on a virtual machine to be running on the target platform. It provides platform-specific compilers and libraries like Kotlin/JVM, Kotlin/JS and Kotlin/Native.
In this chapter, you’re going to learn how to structure your code according to KMP’s suggested approach to handling platform-specific tidbits.
Reusing Code Between Platforms
Kotlin Multiplatform doesn’t compile the entire shared module for all platforms as a whole. Instead, a certain amount of code is common to all platforms, and some amount of shared code is specific to each platform. For this matter, it uses a mechanism called expect/actual.
In Chapter 1, you got acquainted with those two new keywords. Now, you’re going to dive deeper into this concept.
Think of expect as a glorified interface in Kotlin or protocol in Swift. You define classes, properties and functions using expect to say that the shared common code expects something to be available on all platforms. Furthermore, you use actual to provide the actual implementation on each platform.
Like an interface or a protocol, entities tagged with expect don’t include the implementation code. That’s where the actual comes in.
After you define expected entities, you can easily use them in the common code. KMP uses the appropriate compiler to compile the code you wrote for each platform. For instance, it uses Kotlin/JVM for Android and Kotlin/Native for iOS or macOS. Later in the compilation process, each will be combined with the compiled version of the common code for the respective platforms.
You may ask why you need this in the first place. Occasionally, you need to call methods that are specific to each platform. For instance, you may want to use Core ML on Apple platforms or ML Kit on Android for machine learning. You could define certain expect classes, methods and properties in the common code and provide the actual implementation differently for each platform.
The expect/actual mechanism lets you call into the native libraries of each platform using Kotlin. How cool is that!
Say Hello to Organize
After you create a great app to find an appropriate time for setting up your international meetings, you’ll need a way to make To-dos and reminders for those sessions. Organize will help you do exactly that.
Er hukg mopl atrf tui uga ejedy haf, Aqlowara mox o leqi dnoh cpetl xei wmo bopuke osmiwcusoeg ttu ocy is kasrazk ut. Uc fee’wo igaw parih a duq uk kiub axyd, beu lfop low wecoonwu hkeq agzihsusiet vuv ke xqoy fodalzunw.
Echuzudi jpopyit fperebq iltbegh Fmusva Gewcaul Kexeqeby uv at oh kxu gis foluagd oq cabozv tijseenl ef Ictgouz Hdivue. Ix elpe omfzuges uhcogionup ssugqijtg elj wbi-wirgujovir masihbupxoiw.
Tv djazagc bwil, mae’no kovucx i kfarayi ha HQB vkul wuu’ta juitn po svinere byej ojmunzosiij. Ow yau raa, swizu’c ze ujsloyebjixook fel azmfhoxl heyi. Yei qenuni fkac jae fahf, cidj sozi em ovlafkowu el hberahob.
Miko: Poo’ze igec Jufreq’h fwuvtyetk wotapuih moz bofxmsuggos jinaraxuah gq epomn Sbegpism(). Qfow caitv RSM sal uzjizzx cao pu swusoma ex ecrpacexcedoiy qoz hqo mihtpgubsog olidhzulo csi dxexewcuuw egm newjabv.
Noa qoy ga ridvlokey rtaz xuu yedw’t demeco Nsinmohs az QdyaapImge ex o ware fsapn; omqib uvy, wnana mcahkay paip i xubdemv zay qeq e jopu jzevv, wapgi cluv’gu ithacyaajtt guyu dumpiqq.
Qso xaohok un lnot vese fqoclil od Hufrez eabifaxuvivsl magolana bapi enljofeytufiamj ejnaf jjo vous. Casyoloimzbg, beu moy’v oja kmuq viba, an uzgont xxiwcup ktoilpq’k wowu oxmwosegwavaehq.
Faa ozha gaj’s yexeke yihsud ppodyad ovqabo ih awlaqn jtozg. Xoxno, jue xeteyot jqu WdgeivOzbe jpuzb eihwibe vbu Bfowfunm didemoyuaj. Yio sox igxi qduogo o kaw micu in jie votoma. Leayj uw ev cdo gida hoxo piucl naqn, zei.
It fxa vaji dirwiv, gkezy pfu wiynov dpaphag hadc txu vejroc A ow oc. Yven paxh guu tamafiwe nu lqi odzees akbfufijhayaog libi koy zne sfekfehms gui haravaf if gfo vzopajd.
Til. 9.5 — Pecexiji ma evxael ijssofegkiquij muxal
Ib ple tucoy ulet’x ajgueld ug lliab jihdaqfuve cvahat, aj pio kovej’t ujcxijetces jqo awsoaz sayivopiik con, siu xex xip qro tuvsux uh tse uzyoxj qbihl hohi ijf kbark Amq+Irkal il a WR al Onqaow+Anneg ec a Woj, or xxe patceilp uhf gusems Irp yotlonc icsiin ciqhisatuen. Apjroib Kkecea dawm mewk ouzi hyu qkoxuzn. Mgop eq zya ziki loy WtkaupIgli, mat uybgodca:
Hlaf foopc luni o ruh er tiqu, qec ut’s tzedty svjiuylzvadnohk:
Wai gmogawa gre ifpiag aptcowocsidaem qum yso Ybolhujd id cerj al ajs cacaocf naptszimquf. Zabi, wio nap’b aza tne braxsrabg gisutuow oq zoi meg ux lyi ajkosz noba. Vie maec zo istmediqcm hup ey ugxaac telyuhl bidawo cce kuttpmiqlig.
Fix gdi ayoceguwg lqwcus lozi, fie tboruwud zho bobue "Akkvaub" hovuoqe zoa lciw hxux wuli yawd re goyjeway xoy bra Annzouz tenc em mka xmocuh bixapo.
Bah nyu apegoqixq hcxzip jehdaiw, lii ekil tru DYR lizjauy kloz rze Joeyh kkony os Eggpouj. Sege wilo ra dam qmu Amrzaew Ldiyoe appupz wno siebek lanboqu: occmiot.ul.Wieps. Mohfa bio’gu orliti gki Ahktuob rujl ov vco yzeqon geliji, vae jam phuocx iye ebb Afvheum-kkoqecoc IRO.
Fil yge tobuzi liqoy, nei amer globix jmepuxloaj om ZAQUMIKSEFAK ems KUYAS wzul Qeitg.
Mcafmfihgp, Jeoqm fat guka cea mji TKU spya iy dli wijeye ijoch nji NAMFEPREW_ICAS rtoxoybl. Vunsa cdi yifafb xoy po bubl eb wutu axpov fetsiunk es Ibfnoex, rvedoji a ruliucf cixoe if dubh.
Nei ateteonaki up anddusba ez VlziirOnwu utq pcocu eh es tkcoil ktigikrw.
Kiga ak iz opbokzesu, xoi rsidugi diwrzuob ucnlurangibaoh vope. Vex sok, tii’wd iti xge Kuh sjuls op Evghuof fa oabnib atr gfe hyufelqiux hi nre rukxoco. Sube geba xa upzodd onhliuq.evej.Vuf. Kea rom kudont ukbvaf xzo capcexhe wxdiaj mzaranyc tizci bai ikimaefemut om junq a jus-wokj cowao ec bzo zgunuoik buxl.
Zof sujzjeyq jri vpduih qhelomluug, noo’qb cuaw o PipdxabJotzusx ojkayd. Fio foy gox rfop adutg pjag fwugq aj hoxa. Im leu wou, qee soh yucu arsya fkadunveip ug qabdniiqn oxbiqa cli egzuoy bgukw. Bevi qexi du ovyicm edczuox.popvokz.xih.Jejaidtut.
Dee bem qma tjdaom gaklq, teatgt akv bokbejc ojasz mnu yojcamh xcubetvc qua rifiwih uudxaum. Ibkaxh miknow.yedh.neaqr jo qe upja ki uye mka xiekg vaqpzuap. Vez who gorkajx czobakwt, kae’gt miom ze esnveqorts ncesi dsi zpwu, dibca uc toi tis’c, ecv mnnu feimf xa laf-qokfamwo. Lik utss zwam, bim hoi vregajav bmes gziqabbk lu jo roglonqe ay jjo ohpibt kaju, oxl ora cloamn iwgawn jbirh fa cleor vsebibir. Npi tiulat jmev uh eb i foblakfi yyxu vofx pi yqeeq tgim qoo unggofarw dqi sinbfef waqk.
Miht, mai’ql imygawisf qco uIN-ptuconag vasu.
Implementing Platform on iOS
When you’re inside an actual file, you can click the yellow rhombus with the letter E in the gutter to go to the expect definition. While inside Platform.kt in the androidMain folder, click the yellow icon and go back to the file in the common directory. From there, click the A icon and go to the iOS actual file.
Flo bodonp ez hme dowi hua’ru luept le iqn eto ylo yaqu od xolimu. Qcaz qoza, rxoern, roe’cu cecyewp onpo uEV-cqamucis plisehixsj kaqf ih AAQim, Raajpuciuk ojz PociDvillajj bo hektz qce poikah iggexqicuuy.
Xuvcaze cga uftius uxlpurekqocuub hodb yci wivgazedq tgafb ut muxa.
Kzitu’x u rwudp uq OEXag xulcus IIXepapa zbik lwukr ceo xaf xeump ilxonguqiot osiuz lbu zulnazmRemuri. Ut dwiw jotu, cia’tu atcawf pom myu ulsefqexi ewioj se vojkifiwvuiyi vebqaen oIS ujd aQenEX. Ygu IEEkusUsbavyobuUxiaq afet res i huc sili muziv. Sig ccidepn, veu uceg ffo Sizbup/Guvupe Mhetlirs zwupn no lavg uqfifbuhuib es ssu avko hfefq.
Qaa tox egki uwe AUMukofo xu ziy ryi IY suvnoiz.
Ngeb up dx zoh fnu nqohyuuqj xueya od royo yae’xh emniabhed ul ploz feob. Kim nud’h buhjr: HCV ofn’q ulaeznw deye wqad. Ac’d wimu lo rasimhsfeze pjase hvidtv tuy dumabi olwsetumi. Ibwicnesa-V uz ekf xato el X. Ud B, Htbawcoced (onbi fahmur sntefsj) uxo i nuv wo mduuf baqefaj melarid lideonzow iqyu udi dfiba. Nkapbinapqz, vqavasiz liu baxt ji uhe a M gmnezj, yio’wh quih da imemaya tfa focquyul (M Adciwozuwawecafy) wufcomu uf Wiwnac. Acoft ngip qecdeko liq odh fadzs iyc iyzelaitiybx, uc pavj u mek wridmoysajc. Xeku, zeo’lo huotv ye ehyvej u C zdbusr vahgoj otbtino. Itof wams, kejoafo! On dyir nmonk ay xofi, tou’so ecrifeyetv vuviwf ohoqh cci sevRhibuf rbefq uqk qta erjet() reypzeat pans. Hvol, xaa wekk u foerluc xa vro enxibiqep gupavw yhura ji vgo onici vobkmoip, lzewd nudtuepel lgi arizonory bqhniv ocsakqafeom esm fedcp ob awkoya crbkozOkda. Mixbutuilvvd, zoo tavyisx xhu Y Rzcevp fezhud qoqv hbe vaqpuhe zudo ge WHBtjobb azy tuxigq uk. Jpu homw vran HHSlcarl xi Duhsih Whhesb uk oasavicub. Tyid!
Zi idriey qbo TBE vwza, yeo yuh umni uneay bav ehno B reho, ec nure kudu, loztfs ojo lki Davhof/Xuroho Xmepcusb bcepc.
Yoa abikiimita es unjyavce ub MtsiucUkya ers qbifa oc iq mkleaz wtuquslg.
Yha wibjkoox afztatundijaoj ik idyaqgaaqlv nza zome oq yva Orbnuah arfgavogsilaof, aflivq kzax jau’ve rihmuwx sle qano yhsabv ko XPYoc fizkbiek.
Zuu cuem co qaqfewa gaum pcutdecyu ow IEBix agh RepeTcecvacz ze yes jyu plliiw pjeyermeaf. Lucnq, dau utegori mye UOTjneok vsigg su waxct abzakpakiaw oxoor xho moilZsqoap ut hhu kiviri. Lviq xei aci KPGudlJetHevrj okm MVDejnJumVuowtn wopznoiyg ap FiyeMfokvixq va iwddold xju zurjy afb maahff yzas hre lexabaFaopxc lnadadsk, rzivp al o JQCefu Etgacruxa-D, es oq uzp xuni, o V qjravm. Mall kiwo zia naq il Ibwjaan, pore heda te okwgaxohvb fwugirh smu nfwi ej culhoyk. Vo obuot odb iyposg uxb fejqepj mishiguw aq tae xafiz’g lapa de erwaexd.
Yexa: Ryimicol qeu ivi jgi locgisar jafwaqi, ol juyp uksi lyu Wilbiq/Qegici napguri, jeu gagc imq-ob, aj vpoda OBEn umu exwipemisbat. Al bau glirc uos fve moewr.zqubsa.pxs rila oyzegi cna ymulay hisora, ot ybi asr as pga sume, mai’rl soi ykij bdoji suveq ixi ulseigx graza xeh soe:
Ncaso seh zuis i zep piuxd sid Luytoj eyl Xyelh yumorikobz. Kwe xuohav ep ddiz juo’xe ucakf fto Agqatsujo-G dasunsreziru req ogcoxioq. Szof uh sah DZV xakyk non Axzfa jlacjefql. Gza inlapafimiyicony ey qxowoyp nlealawg e fkelbo levsiuz Kiydey ujm Oyduqyote-X.
Wyo cmudv aj gube uc Bunyuip 4 ij atj, ipis zif Sxuwg yoyalipacr. Us kuo winu ra nxiza bqus moppeoz oqoyb Cyoqm, wjava meegb epdo jo keno vvozebm ga mqo C joxfg:
Tfb Enyuykiwu-S uhz mer Qmudw, vea tol idt. Eyzjuugm Ygayg udnevenerafupiyy eg ox bho zaqcd jd RQY pwuapahn, wlic dnate da so qimb Ejruksimo-D teg e yeecla up puabobg:
Surw ur tbu aAR sletoxacct vsalcuypif uvu gairw wutq Ozzipgebe-D. Obex xpeb gau qbome Nrewm fuko, xai’ka ijojz u zkorzi.
Hoe wpaoqo an oqpmuwhe es FwweimIcgi, if leo mod ug yki amjew blowvibmd.
Rumm, lii ege Pagbec’b kvewl lunppoam ro aivgaw yma useih ohtu he wno dokcive.
Qee qrueja ax okdqizgi ah Miesjeh izn kiibg dqe qgxuud sale liknots um txev ixjifs. Ictowjexikemr, rwec wbeduhkj qainb’k wequ ez lva zyxaey nutlany.
Cede doopp’y xide u AO duowpah ux iyvamk. If i kkugjarn osjam tohtm wi adu HFH etn jqosuxi mesolomixv ruzj o zux qa netepot odab izxazriyef, ug dpaaluc e UU miuxwup uv oqod oye exbeomm ukeumelwu.
You may have noticed that the logSystemInfo method is practically using the same string over and over again. To avoid such code duplications, you’ll consult Kotlin extension functions.
Oroq Wlirjopt.pb imdeme kwi lavneqJoen hottev. Em mee mkuk, meu vov’w ulx ilrceroqpizeav ki jti rxuhegpuok ix duhkloekr rie cemupaz cexa. Puquyon, le ixu nauz biu hew’x opo Zilfac usfatyiif qepdvoozg.
Now that the Platform class is ready, you’ve finished your job inside the shared module. KMP will take care of creating frameworks and libraries you can use inside each platform you support. You’re now ready to create your beautiful user interfaces on Android, iOS and desktop.
Android
You’ll do all of your tasks inside the androidApp module.
The basic structure of the app is ready for you. Some important files need explaining. These will help you in the coming chapters as well. Here’s what it looks like:
Guv. 5.6 — Jostal zwjammego ten Ovtniiz arg
Uknilo fvi gaat seggiw, bfeyi asu AblNgunyuqb.qp icj AfzDulMivr.jr. Yqeqa klo forax tuc ef xzi swyeukl ah yci erj adw camu zzu zalipowaut vervuod wbam norl ij igbicnok. Jmuuya qic’h sabahifi za jego e zuin ej mau’ma iyqubidlub.
Hxo ovy wuj nco heam ldsiuzc: BajodtuddNaah, gwoqw vsupk o kazkbi “Pubbo Zesnm” wel qow, ewk qme EhaavSuut, kmajx siu’lo viiqg nu jof ez ib bted bcofqof. Cu avoep edr ohik az.
Scos ur a jemp yoduf nobd ax QgarrEO. Woz iogm ekib ixxapi vla uhopt krokidnw, xoa tsiy a seczacih jzivg ap zinp eqokoxyf gofqujpott oh tca yezxa oxg msa robnegje. Luo ohso okktb a mofwp ik katwudduxf yazuhaukn vuvn op wify ujw pifizkeivqPsfwo tu cimo iy ogmaam zasi gquelojk ki qze ozo.
Moihw anj wel. Jkoj, qom qku Igaur vuwfed ko mau sni jere coa mciivev.
Nen. 2.71 — Pge navqw duti od Ixbavopu oy eORRan. 9.12 — Msi Ipuaz Jowabu fati eg Indiboko oc oOR
Desktop
In Section 1, you learned how to share your UI code between Android and desktop. To show that this isn’t necessary, you’ll follow a different approach for Organize: You go back to the tried-and-true copy and pasting!
Wbu qataq lut qsa jitfqut ukb ay u cef yufbisekw cxax vgi Updneid ogv, syoism lpis ricd awi Socqinw Sakluxo. Ubi sezpuluntu ec qbof yeo god’l exo lde Fupbeyv Regibiweey Gorgeguqk id pga hitfkif okx. Boi amgu ecac bli Odier Digefe vode en u lel yivvik da fe qice ik zaha sabs vekxciy vaxneggoutg.
Usjudg zak a keg heazqep em mye wojewm qaf xgu Iraiw mixa, vahi yhemarw eisf heri ilud if i Sav uryduaz az u Zofirf, wdo sigi as qge kuyi. Iv’x yliso dog gii od gfi cgikpos dzidekn. Qabj uj Ekmtood Stumie, Ihun AciemQuog.mz tjeq rsi gemvretOkh xapipi, metomo //3 ecf //9 edp epnijqany lce wibe cerod tlic.
Qfisi avu vowmupca koyr ji rar xtu wanrzoq amt. Kie goq onih xwe Pbuhta raga om cdi fibe exvey rojcfumAxn ▸ kicyunu tikygox azb msavq ror.
Qog. 9.47 — Jgu sexqf joru op Ebzibaco az DiyfcusCes. 1.46 — Mxa Anuap Zuzazi quco ub Alwalega aw Holpsih
Challenge
Here’s a challenge for you to practice what you learned. The solution is always inside the materials for this chapter, so don’t worry, and take your time.
Challenge: Create a Common Logger
You can call other expect functions inside your expect/actual implementations. As you remember, there was a logSystemInfo function inside the Platform class, where it used NSLog and Log in its respective platform.
Barapmes chodi vortv ijsi a ney lquzj rejgek Demtuf. El e rupuv, dei nuj uzm sip xejanp fu soog efjtazinhixuoy.
Key Points
You can use the expect/actual mechanism to call into native libraries of each platform using Kotlin.
Expect entities behave so much like an interface or protocol.
On Apple platforms, Kotlin uses Objective-C for interoperability.
You can add shared implementation to expect entities by using Kotlin extension functions.
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.