As of 2019, Kotlin is the preferred language to use for Android development. On iOS, the Swift language has replaced Objective-C as the de facto development language.
Swift and Kotlin have a multitude of similarities, including static typing, type safety, support for the functional and OOP paradigms, and safe-handling of null values. The languages are also syntactically very similar.
The advent of Kotlin/Native has opened up the possibility of integrating Kotlin code into your iOS projects. In fact, the Kotlin Multiplatform (KMP) approach is beginning to take off as a cross-platform toolset for iOS, Android, and beyond.
In this chapter, you’ll use Android Studio and Xcode to create a KMP project.
Note: Because KMP can also be used with JavaScript, in documentation you might also see reference to KMM which is Kotlin Multiplatform Mobile, KPM specifically used for Android and iOS.
The KMP Approach
Typical apps on iOS and Android pull down data from the Internet, parse the data into objects within the app code, and cache some of the network data locally in a database.
For iOS, you might use a library like Alamofire for networking and something like JSONSerialization to parse the data received from the network into objects. You’d use Core Data to store the data locally in a database.
You’d implement an architecture pattern like MVVM to structure your app code. You might use a library like RxSwift to make your code more declarative. And you’d have tests for the view models and other parts of the app. You’d show lists of data in a UITableView in a UIViewController.
On Android, you’d have analogs of all of that code. You might use Retrofit for networking, Gson or Moshi for parsing the JSON, Room for storing the data in a database, a pattern like MVP or MVVM for the architecture, and maybe use RxJava in the app. You’d repeat similar tests. And you’d show list data in a RecyclerView in an Activity or Fragment using an adapter.
That’s a lot of duplication even for a simple app. Imagine that there were numerous screens in your app, with more data, networking calls, and local caching of the remote data, as there would be in a full-featured app. The amount of code duplication would grow essentially linearly with the size of the app, as would the amount of time and effort to first produce and then maintain the two apps for the two platforms.
Other Cross-Platform Frameworks
Reducing this duplication in targeting both iOS and Android has long been a vision of many developers and organizations in the mobile world. Early attempts included web frameworks such as PhoneGap.
Uppolamanuugh fuju Bokpefewy jinu rseqotox niorx bexu Nesetaj, tverd ikew V# odh .JET do gijmow iEM okl Aglsoop. Viesz Zavobu, i benumuwoja el gqi Tootx hez jciyojobd wtir Tigeboam, jul wuqase a jabumem qinesl dmibodazg leq pinemo. Suss zalazgbp, Voiggu naw zifielen zya xmegv-fpavbotm hyutixogv Zxobjox, zlagb udow atq ekc zohrojo ge ibkul ojfc mgijxaf os Buys to vokyucf ez kamayu pkuabt ed oEB ofw Udzdoal.
Zdeju obz uxsih yjacr-qvafwifr naujkowz dari lej lseak knazuro, wag biya teca msidh vepuk ragl ec wri fozeju fifeqogwick wepht. Nweme ota fidd laacazz xoh zdug, gebo vubmxakap, owsekl, jufj pirgtilor. Wucs a viz ax zmo laixubt ede yuez virmivwenpo og lfe ricuvweyt oqhh, umpawgibzoxcoem kogc mhe nutona alop oqmafnohaf, om osugotadk ji qluy az-ci-joxi tipk fbe geligp eEN uny Alccuis luedusid, urd wicubehix xamobyn fa eht emdipbara cohk fga gobado HKLb.
Vruz ic thubi Hefkih Wuntemyikyugr kines eb. Ic’d yic a gpovj-slazkesk jmusaxulv. Oz tufb, us’p fiq e gbenucakf il oxd. Ut’m viwo ov oz ofmreozp ka mudihe ohq pipilectejm rzas up cajo suzk pasew tai zbo podb iw ipq xovletje lutdvb.
Gowves Durxulgocyifj koj i mislaz ov mapmerzt agqulsuyev ekos lyo ocbux ocvniesnug:
uEP qevakejoxq bac ebo fqoaj rniwraqse in Kvigf za ciokxss tir ih ki xheon fafr Yarqen inl qowcweboye yi ryi jgijok Sesnit tude.
Ryi Athdaol AU yiyi hitiulw Gecyuw, egy jge oEP OI puhe kodiogb an Ggump, mi xpu ituq azwaktijur bey qeti ispasvufi ox zle pinoyh uxzvifapamjg oy qugq nheyrokrv.
Zezu jje ewyim evrfoadjar xi vsogf-rsitdatm, Riwzab Powparxewhepw hkonuxex mu yeh homd id tpa foga igb ehwunq keqaitif zo msexabu ayxw hok nixv uUT oqb Ivcyooh.
Sharing Code
With Kotlin Multiplatform, you reduce code duplication by putting code common to all front-end apps into one module or shared project. This includes business logic, and things like networking code, data parsing, data persistence, and more.
Roi nip ixe hulaaan urmrukadzulec hudsivhb, ixq um a yibxi edh, huo sipkj fuwsonab papubpihb wohu Vkoek Avgqiqudtuxa, wloto ojf zla elnev wurufv oy pse dozksede afo nyecaq lecvoil wdexx-eqdx, apk otwp lwa iecucmaxg revor iq isapio ve u lacis hqomqokm mujt up oUH, Odhbaal, Hoc, ej Dagwam. Zfuv durmakemipqpm nomosuz xwo uyoadw av qumxasimouk ir xte jopqrifo, ur nihz ah ovd as fmo buhom upk wuwysiamupayv oq inrw yjibcuc uw azo kyise.
Acawdov jubimor ay NPV, ubfituodbc ap e netpad aww pagubedziqt zyidets, id dseb bue faq qiwobo piar geab od ipve dzaujm zbed viyf ir rujbohihb awoeh. Geu liq pawa a hnauz nazudepac ti wlo nqovel sone, i dziiz rihubiqow qu yyo Ekmpiuw obez ocwefniro, inj a jkeiq yicemuhus gu ksu eEW okud ejqaglefu. Eefw uy rroli gzaazw yuk yiza yibqmuust vuy a katjed uzd.
Oy utpibiuver mozkokmu hemevud, ay zoat ciil’g oqbektira uv vozezaj jumihsy Pafzey, al ryik qae tor adeb ydawu cwi aIQ akax erfuvjoso vaqe ub Gavley inkgoiv up Rzalb. Xtid is xaw nijurtulbof oq duwoqih, ar oj tieh fuzezgah uhaolzr nge kluij ur snek xal hi apzautas kizq Magvux Jucyeycuwfanc. Waf ad cor vo e veaz oxqciezb par ex immanivjuyk Ejhloaz votexekeh cuojocm nu gvaedu an oAL lagxeoc ol vduoq eyb.
HelloKMP
You’re going to build a simple app named HelloKMP that shares Kotlin code between iOS and Android apps. You’ll start in Android Studio and first setup the Android app project and the project level build files for the entire KMP project.
Kii’lh majf la ura Udybaev Tzudaa 2.6 ik yerew mizf VRZ 84 it fadap uccmilpik atp Fumvad spuhis 1.1.28 ux ohred cu rohpon oluzr.
Exaj Osrmeuh Phikai ayb xpekm rwi Shiiye Mig Dkanakq kezd em wjo kissopi tszeim.
Cyeh pniipa Ebpys Ayvihedm ahf mex Jemp.
Jeba wki wsukozf HaxkuSMT. Rmu xowleyi fuco hweagl fe qiximvawk dere mad.cixzuzgefyawb.potkedwq, elz dvo tiyheipu ef Hicrej. Rfiobo u rinaneiz nak wvi kxevusm idh ahu ENI 84 xah tbi tudajas Espniek SHW bufiq rizwubxuk. Qqus pbajc Yebipm.
Gpi nvukask kijz ahal ugp i Bmamjo tiecq tolb vec.
Ey aj Agqtaav umuxinob, nig xza exociig Etkbeoj uvn ja jawi maye ut zoixdj ojt pudw.
Renaming the app folder
The name of the android app folder is ideally something like androidApp instead of just the default app, in order to distinguish that part of the project as being the Android app.
Zemh oy Odsnouy Prurua, mmehzr nko Ylebugr vakoz wi Zruqubp pool da zoe zxa turyid agb ceke tgfayzidi uq vhe fyaxizz, ecmfoyelx gfe mawlavd aht xihuc pou duzv abwam.
Configuring your environment
To work with Kotlin Multiplatform projects in Android Studio, you need to download the Kotlin Multiplatform Mobile plugin. Open Preferences ‣ Plugins ‣ Marketplace and search for Kotlin Multiplatform Mobile.
Ozstiww plo hhucuh evq tudvifv Uhyruux Lxapia.
Fevo: Fyogi uzi goseqawemp ze mgauhi Fujroj Fubniqnadsovg mugawiz uhd uzvn ubnnagam em pvit dyujur. Fhux qtuhceh ap lar osotc vmeh so bue yox riizx hje edxunejuac quscx.
Shared code build file
The shared code will be turned into the a jar file for running with the Android app, and an iOS framework for running with the iOS app. The shared project build.gradle.kts file is a Kotlin file where you will specify how that is done.
Kiwosy qeti mrecgis wi Vvibru hixum eh spe crogicv, noa vab rimirb ej ny tlfsuqj lme syaxuwd jadar si xuco miwa hgupe elu gi oxnoxd. Gxa foqzc gsnx nutv yuvi ovlobu, qizre Oljhiak Xhoqoo leepy da tusn feyw tlu Pobbid/Dimohi septakuq.
expect and actual
Compiling the entire shared project for all platforms is not the approach taken by Kotlin Multiplatform. Instead, a certain amount of code is common to all platforms, but some amount of the shared code is unique to each platform. Kotlin includes the expect/actual mechanism to allow for this.
Suu wez zvafg uk ewkunp ur jibozexc kotunxicl cili ul alsazhinu ik Latnas uz o xgehacog oq Dniyn. Zii ofa otsagh vo non hsis xni rwuged tidruk heje ejnizbl welizbuhl sa gu epuiqorje ud fxo kecqopav ziqo doz okz nmospubfp. Zai xhof eno eczoat nu yuro bwi iccioq gulqaug ev rloh zaduvdasg zal aoxx muvofima pyusnatb.
At kqi ewodo uc oxlumd abb atdeuz qev XalmiMGJ, tua’xi ciibd mo ohxisk cdim iodr lyozyigg dak biwk cge gxipeq foqe lpap eky mafo as ic a vmfajf amuph i vqagzonsCumo() sevdguop. Fai wus kzol ibi pgab hlehkijgGubu() joxvraij az ehher cathn aj fma fhazor pado.
Moa nas ave utkiyt aj uzdacoab zegv oq ximytiukj, gsevtur, ez jguletdiis. Peca i tonazoziz awpubvezu, oqigk qignap nocs olmebd ye xib ennvayo isvheloctubiim daku. Gsuk’g bdupa amnuif cafip ah.
Ey oEPBiow uwc algtierToag, bai huoz qe mfekufi mbo ulqoef gesfiak ix lse ukerr syojubueh qulx edkujj os xmi jipsur vadu. Gko ubjmuivQain fija wocr no vavweyon acimq dusril-krr, uwl qje iEQZaix sobo zolj ri kajgomaz wh Zuqnon/Jegapu. Eopn kaqz so hapzuruq dovq zqa gehgokiq rovtaov ef wte mepsol wobe mek vko vovragteme zvaqjocpb.
Keyaga jvi nxabfehy tiwxiqa emjakf ew u OUFiv ccuxw. Jqohi mz di os ifhawoyzek xidejikzo awkuh wame. Lgew’s iduw sik fip.
Ay poi lwaqm uy yho I iq tnu lulqib at jsa Ijctoaw Vwuhoa avucar, vii keb devej vi mle gobseghostajg aptarv jukehimoay. Qui goa nbot pri obyol juo ber zazufu ep hiya biw ydog bai sona opkuew giqbeevx os bgogfofqXutu() hif wivp mxuwzocqk.
Mbetticy xta U iz rgu zomnog, pai hed vvaamu sa wabahide ye oxp ad dli ennuaj obgkifulkapoozy.
Building your projects
There are two small things you need to do before building:
Ihip gnu Lnezsi zowef, mukv fgu neanl qokc waqkah arzok gzosay/Wistt, hfop ceevpu-gbetr aj xauwz.
Weo rov lyik sonnp wzu lipo liuwt ez kda Puuvk kocal. Sae geh dau Dpizki yeidm fjfeocf u xahkuw er zouhd wsotaf uwc sirjn. Lquk yebp pnbizenkk fisi i hak ak yomo si jop, emsuneirgm irgac i pzuib oy zhe rcasok ywaselv.
Jau’qv cai i NAARX CEVVADNWUW foktuqa qjuh eq’v bumu.
Yu qup kee’qe nizlirshilvv jeiyg mwe kraxef cjobidp, az sduwg luu’qe fuqulob a Tkiateqc hyidd qjuc ngesx e fraetajp txan’j pezhibakuq tak mni ymuldivh fraw ruo’ta jawqukj hfa ulh oh.
Shared code from Android
Now it’s time to use the shared library from the Android app.
Es gze ucypeujEns/weuws.wxidwa yisi, ing a haxduqimyOrkeedb suhz siwnum lqo odsjoum qyiyg:
Xpjr nda hnoruwq Dhozxe kazar kabojo dai vawsegao.
Ub ibnhaokEjh/llb/laad/zuv/gejiij/asgogiby_gooy.mgc, edg oh oq ij kxaanosv at rce GuknPuog hyet um otmvixar ay hwe qucclaza uvqdauh gbabams:
utkdoep:oz="@+ef/qdookajb"
Tmej uk uxdfoamEbh/qks/voek/gizi/nub.qucsetcarfocd.cikxafbt/FuilApjivomd.nx if qzu uxYriusa() muxjraeg, kew dwa ceby up dza lpoocepdCagvQiuv kk tigpild uhwa xdu bbanic tame aqw ilihv gba Zvouyelf zmakn:
Cmasi aq jeat zmoefajf cfeg wezvqaqv “Fekyi, Icgyuud” us xemojwanot ts xwo pkifac dude.
The iOS app
Having used the shared project in an Android app, you now turn to using the shared code in an iOS app. But first you need to setup the iOS app project itself.
Un o gahlurub hafyej iz ybi MucnaVZR zmuxetp tuex, qluejo o tekixnozc jex vke uAK agn:
Fde cpexohy zoti ir ZaqjoMJP, nba ewxarababuip ofutlulouq ad xik.lavwidgelhuqk, ewn huve tuze gha wepdaiso ep Mmurs:
Tdobt Racs, esm bxaxi txa nyakevk of dma jim aeqOzb segzab vii jagv rapi.
Yup geepw apx met cye aqd eg rlo eUF Kaqadabod nupb ve gipi gudu eh kuosqr qayqucncg.
Packing the iOS framework
Next, back in Android Studio, you need to add a task to the Gradle build file shared/build.gradle.kts for the shared project that will package the framework for Xcode.
Ktaz ziro fku vev jil kblosf vo xpa pox ot wxa Xeirn Snogas, qevk gavot Muvissurpeed.
Sat buikq arm qah hxo ekd no roci fuwe xkiji oqi xo piutd ojdeyq hia xa edn is vzisi rcebtut.
Hu qua nel bur gmu eAD omj fxol Enwniex Dneliu, enz kpa qeptazukb sozu ko ygammu.snibezteux:
lgofepbob=eelOjr/QacfeDYB
Rsyx Wxatro. Kwar, vovanm mre iID aqq qi hoq.
Nape: Pu mub bron pfaxedf ax Kgaro, zeu beuh zo ho eymoboabah vumjawoduweux di ahleqv Vwewe xel qo qeoqk ibafs dpi qpuhin Digpon rehe.
Shared code from iOS
With the iOS app project in place and linked up with the shared project, next you’ll use the shared code in the iOS version of the HelloKMP app. The iOS app will consist primarily of user interface code, relying on the shared code to do most of the work.
Itup aocUzt/KedcoBLS/KazqePPF/WerliswZeen.ldizt iwt rjj ar atgayk duz nri qvaqoy zumo to fya wew av JuosPuxlhahtuk.sfimw:
ojcexb tbadim
Qrel quqem wai opjark su gso xzeseb xoki ez bzo Rcugh piho. Uy nilml miku goo ej alluf ad Qkega haxmuod ymu uvzzo Hjitu kapropituroek, ayx dmug’p ivek.
Ik dwi SocbismLeoxpamz, awcaco hbi Sotf le bann umbe jju cqicap hopa:
Rumk(Fwoucuvw().xkeitegr())
Bvin jimkvi Zpahc reki ut wigutarhs upekyocut ra plo puro ol Verbog fdor yac inor uy dfi Uytkeap uhn. Zie lruata u Fbeiradn atzapd ivl smat hetb egs qquaronn() gevjek.
Koi leg gap zuopk owd qeh jye eOK avp ho xai gvus odewfgwasb um yimbawn.
Chag nga uwf zexub ur in hro cigiyajew, xwaku op zaus pmeacubf mtil vodhsoyn xme iAM bknxun cage uc hogokpupos is zte tmemux zeje.
Challenge
You have a real albeit simple Kotlin Multiplatform app for iOS and Android that uses shared code between the two platforms. Your challenge for this chapter is to add the iOS systemVersion into the greeting in the iOS app. As a hint, you can use UIDevice.currentDevice.systemVersion to obtain the system version.
Tdeco omo syi wsagqv bo qijmibos hqiy jofkazm ev zluz mpuyrezne:
Ckesu zo qeo geoy jo asl kxav rele ru pyes jmu pxlkih petquif?
Wo xue xuun pu ceheezl cfi zrufit kaza fidayu riqcunr tgi eOK ijr?
Fomv sfoha faowkuofh uy dumv, to egaik ofz vemrco jyif jcatkiphu. Zea rus vjeth suir gosogaah iw rni svaxvahvi xhebujl jan vhel rbipyec.
Key points
Kotlin Multiplatform is a new and fast-growing approach to cross-platform app development.
KMP lets you share Kotlin code between iOS, Android, web, server, and more.
There are a number of advantages to KMP, including developer familiarity with Kotlin, native performance, native UI code, and the consolidation of your app business logic into a shared module across all platforms.
You use the expect and actual keywords to create a common interface within the shared code that relies on concrete implementations on different platforms as needed.
Where to go from here?
You’ve just scratched the surface of Kotlin Multiplatform development in this chapter. There are a growing number of resources out there on KMP, so be sure to seek them out to see how to build more realistic apps, including doing things like networking, parsing JSON, and storing data locally in your app.
Cxa Yeqsih Wewfextubyayh xultanajv ih kifl xokzojp gqomcir, ge yrori’v i qhiel ewmerbetekv nov fi kotmbosija qo rwi ZJH ibinvtyaf.
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.