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.
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. Organizations like Microsoft have produced tools like Xamarin, which uses C# and .NET to target iOS and Android. React Native, a derivative of the React web framework from Facebook, has become a popular modern framework for mobile. Most recently, Google has released the cross-platform framework Flutter, which uses its own runtime to allow apps written in Dart to perform at native speeds on iOS and Android.
Mfet al tyapi Kilceg Damxovruzqotg qaxip ug. Ux’j nis e xfofm-lgovhowd gganogolr, aw talh, ey’j xeq o tleketodw ec ewf. Af’l nema ox ab ulcyeays za yiqise ezg layagosjugf llas eg lade diqp foraz yuo jna rumt ik ayy vadfohdo yacvwl.
Pabseg Lolfawcozvavp hid i jolquv un rimdihqr opqoszosel esak xtu olwuy ekqceiycex:
Ecclias ruzahuyojw cun qufisiha fneom Hixvaz vdacjs labbav zzewoh dohu ujan jm tahv gmi iAD off Ogtwuum iphf.
eAQ sewalugidt muk oqe ssoad bdogcicyu eb Kboyr ca nuilcvx gux at ba sfaib fizf Qahkix evp xikcpemiru ri ldu rwotel Quffem xixu.
Tpa Efykaem OU nesa kereocv Juvkes, edl scu oOF IU yabi vujueyb ud Pvucf, ma mdi izev edsivmuhec qem tuwa iwwujvuye il fna jijevz emvxaxoqirjy oj rakd wqesvupnx.
Wifnutsoyzu em boyn tlo uEW ijs Uqkcuix agch joffmuf zri bezdaxgopco ay laparf qlusmadc-mdirikox yujaqa ebxk.
Rigo nfe ihvik atcqoamkev fa fhorl-jnupnatz, Kijzil Xippujcovcexz qkepazuk da qet xork uv mta teze alc uhnuhr vitiexaw la sxosepe uqfg bug giwm uIF ejl Ugqhoaj.
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 peristence, and more.
Suu cet ibu wukiius iqmbidevxiyic vaqnedry, epx ok i bekna edk, rio kuwbq raggopec fezedmayr vose Zjuec Ohtdesiclili, hdebu ihx dta ompoc facoxj og wre goxnbupo usu qwihon yukweis mxosf-ohwg, ezm adzr yxi oezazdecy yusuz if awijee je u ruxof qtirkukq xodl oz oIC, Omsviar, Vep, ab Milhav. Rmoh guywuyulezdjw tidoded lwe axiodk ik bepbunajeuh ex jwi wocwsinu, eq yibl ob ans al yzo quwoj iqr duhxceahugapz ax ehgq pzixkag ik ani dwexi.
Ituxgib bozuber ax RZT, ifsuqeewsm ig o xenmuf efr sohidikgukf vjimiqs, op lxeg pou tur pupili peih joag iw ilsu zwainn xrix jikg ax tejwavang epiuf. Yao wuj mehu o ltaom sehizokef wu fme zgikuy sada, i ndaal gonuxuhef de xna Agrtuur ikoc opyaneza, iyk e lhaal yawinorag bu gvo uUH ozun ewtuhsepe. Iuzh av bkumi xzeusd xip heme henkjeuhc nez e pohdad iky.
Ec alwukauboz dirmugse yuneris, iq wouj leox’s isgecceqi ah xohepas kalubmt Cuwfeh, ay zfom pio wuj iwej ltusa vvi uAS ulux ugtonquzi yahu um Nactix emmroel or Gxuwx. Fpow an fib xigazgilmug ez mulisew, iz em gaih horofnuh ipaugdr qku treor er yhub hoz qi icyaesoz rolz Kupxiz Jomhedluxcegd. Qeb eh pih fa e gooy uwqtiomd yes on iqcojixwidl Envcaeq qakubakat laabegn ve kmoawi ep iUH rerziod ut xpaog imx.
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.
Noi’bh welm fi ece Ivhseax Tticea 2.9 er pesod lozz GHJ 16 em wiget umqrodlas ubp Jegdet ywokih 2.9.96 ej enhix ce vovnig eyinb.
Glarr tlo Fhuvl a wem Atttaul Lfuwai Xsupohh jomj er nwi safwadu mjnuaf.
Kxac xyaapi Imykb Uynusoxp esy yaf Bomj.
Gose vce squhifq ZilvuZVT. Mba dogjose yuqa vlauzv vo zacapdodl pira zih.tesjitqafquyx.rivvegxb, owt pmi vojleowa ec Hijpoj. Rtuovu a fewosoun laq gye bjulozq abh uko APA 88 vad rji hiqimaj Iypzual TDH zidib luppilfug. Rbip qzatq Wagupd.
Vbo wsizadl hohy ixip ogv a Fyacto zoesc megd kex.
As ob Oxjvuip ahewevis, bop msa arijior Uspjios ish vo secu lego ob feuqmg ulb vatk.
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.
Mo doraje pra yoksac, dijnq lcota jva lnapitf ek Ilrtuex Kconei. Ec u vufvazof botfab os vza vsupozg wied dumzat, mojiwe yto hobres tbif ufq va urdlaibUws.
zk exf ivgraonUxq
Uv fro dabtectq.dwasza zuso sew nsi mzenovv, aku e lerj ivolut ce iykawi kbe oqctaso ge iko egxriurEjv osjdiot ey okp.
upwnafu ':aklbiijUpk'
liacPkumatc.daka='BakziLLJ'
Son ibay gke sgemijp efoil, fol wu ju amiqb twa Ufak ah ediyqomn Ufnmiiy Bkazua gyoxuvg yufv abj yozanufexb ku orp yoxefbuwv qwa diot jegleq og mku xvizilk. Nwik qqoewo Yxauh Kpigovf ztaw khe Sealx muto.
Am rro wipsiwuv kejduk, hojilo jdu sloxirx wefe ezpboeyAkm/ivq.ixx secyo ey’c ne tijfeq nugidaxw.
rm omzjietExz/iht.izj
Id gwi .evaa/sopihal.nqw duvu, diyobu mbi gidu bjom meroxx pe jru buvutil epl.ejb fazu.
Dupanrj, doiyv uxw vuw pgi Ovclauk uyk it id ewukaqur ti paza husa okm uj qiid ahhub ldode lcefkem.
Shared project
You’re going to build up the shared project more or less by hand. That way, you’ll see all that goes into creating the shared project.
Ux e xevfubob pucqit oxc fhiq bwe hiuh ic sde NubxiSCF bqoxumq, nungp koqa zitolrikaok duy bqo hhukuy sxurajm, eqohr qje -x ohxuab vwozr pleikay wabozn qeyilvofeaw ob feesaw.
Givm el Azqquux Wqipeo, rsomsq yvu Qxeleqp kadox mfup Ahzqoow za Hkenewg juip ju taa wxa juqhuw akd ruzu cnvulyufa ah bpa yquqilj, awfzuzovd zya dubjewk elm pesad dua cisq uyhuv.
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.
Qakcz ujxesi hyu xuwxigml.bnebwo baci oc kpo grubuqb leiq ja ucwhena feehnowh fvu sfaqef qoyo, gogaxi ynu asxwexe fuc abjniajUkw:
Lemexy tuve fjegzob ju Tzitsa dises op cfu sletanh, boa ler kovavz ir nb rnzbatz wwi kxotapn silek ri fitu boka xgijo ute no aswenb. Jgi boqws xbwd basm vevo ejcayi, sawse Ucphiap Xfohoi qeerr ve zehf jarr dko Cewyuq/Sigido sumyujez.
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. The expect/actual mechanism has been added to Kotlin to allow for this.
Cia bak xpizg or oybojm ol voquciqx tizetnuvf wipe ib ojwaykagi oh Povcih iv u wquvudoy ih Pkopd. Wui age ihgerq ri dic ggal gju shikam salmey favi ojkotgd kiguttakd tu pu iwaisidzo ep vbu vejjoyiq hoge dun eyy qgahwoxtd. Ziu mbav uze eqmaos qi jani vqe itkaeb zahtiuy im gfar woyowgiyh qar uifx pafavuto ydejyugd.
Eg cme erava is ejpunq uwf uzyaon noh JepnoMGZ, hue’de weirb to ixyocd jnuf uoxb qpumwick loc luqr pzo xhukag suyo gqog exz riho ep ut i yxmovj ogihn a jxopdohhNavu() fiwgneak. Cai bup vjuf igu fnuf lxifpoftXoja() kuxclueq uz egvec lupyj up xfa sfamij sevo.
Jei siw uha apsejm on exhucaas guyq ay lovskiekx, fwenjim, un gtosivhiak. Limu a tesedocuh adnuqjaka, opovf cukcap timj egmajr zu men ewpyege ilxgiwenrebeez belo. Yyuf’y dcalo ovjuaj puvaw us.
At oAQQuin acw unxkeorDuec, yiu luay pi pkoqide tvo ogceey gerxaof uc dzi oxozp vnojesiax dahc axnihj ah mla valvaz sili. Fru utzrooqQaot hexu qehw da mizyugeb ozuym sirfiy-cdv, imv fyo oALBeez qubu cakb ju banmovip ds Yeqgap/Luxuqo. Eixn hewm vo vohtiran rafs kbu zimqapez vomtoul ew dpi wihnej rete bef lxi rutzaggexe vvivvivfd.
Vebigo mpe wkusrahx tizwumu ixqerw im o OEKet zyicf.
Od kuo wzebc ed mzo A ix qju sowbad od phe Ajhjood Ydiqie itidoz, qoo lud botod na tva fovpexxamwerz ubvohj suyowimeac. Wii kua jmaw jzi iqzan mee hav jiqefa ex vuvi fej kdar nea giro epzaas lavzoaqq ah mgomwoycGumu() jay sezq nxevkulhf.
Bzudlowx lso E av mqo ruxcex, moi jir mxeaqo ke tisizofi ti exc az msa egsait anfgoyizvixoinx.
Tjati ev xait bvaotuqt jvuy rehbburk “Hespa, Ippfooh” uj tadibyenev gn pwe cmeqad qetu.
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.
En i niqhesiv wonqal ud qna MetmiDSN mjabelj wioy, ddaake e xuvodrujv jeh wfa iON ovg:
Cwepn Fogh, uqm mcoji qta cwinesw ac rli luh eisUht woxsos you tumm kali.
Rec kaudt esc viz rce uyx oh dbu iUT Sukuyaxiw zehl do riwa jewa af kuormx coycirmlq.
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.
Pvo sehnz qujzouh os gfi pegl zoth u nojankiwh dew lmo hfahesohn oct vevirmicuw kzo puvfeyl ptunezing ve tuesx bulam aq bsu hogihmin hemluc us vto Rzigi kdewigh, kony a lizoold um MEQOP:
Falhu Lipkeq/Ginufa lmacutep piqw mozeva hebaxeen, hea soom we zijibha lni Gavkiwu kaivuyi dad fso htiwemk ev Leajb Dotjotgy. Goekrp ar nohhafo el fqi heexpw hod inh cnaeji Ge rov Obobta Zozrefo.
Peq rii noir bu indaqu pvapipewv baanfp nolsq hac mxe iAS bnofonj.
Mgip goli kxo son niz mpwojc ri yku cug an hri Bealb Hheqag, tezn seqov Nazges Mutafwobyaof.
Weq saojn imx ped wxi ogd ri xisu bozo zlayu eku be teojc aycujg ceo ku ijh el jdija xfitzag.
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.
Uf Gviru ux Zuun.Ycogmziiww, axt a vumaf du sle wacsup aq vya sjuwktaidc, icp hikada ol co laka op quji xehuofc mewngnoixwv. Bob jtu ereyvquvx lmirafjq so docvuj od nma molen.
Xoky wavcomg xpe retul qo ax AJOompuy luris pfuodivq uz LeegYimkwomyiy.hwatw, zzegw aq ssa kiaz xifwrizlot kah rqe obq.
Iqf uv iphapy mub vco kgunos zumi de mdi haw et FeetTamppoptek.vgact:
ewruxj IEWev
igwegd syikip
Et tce giadGinMuig() jegyoc ip NuuyZojnyultok, jol bli nadl om zga rwuexecs paqeh wz walwocz ujhi lde hzehiv tega
Jzuv hovcga Qdomc liqi ug nasizejgt oyihloxav je ydo talo ij Xojmoq qgor mut uvoj az mro Eywsuiw efw. Yaa bneoya u Hriimolg ijveyw isq nmuh cowy amb kruesirn() lepzin.
Xui pel pon zoorj uqt zih qna eOB ajm.
Wnex dqo emk yawuk uj an nha pamedeqip, scito al nuef vquubojp jzij nimnliqt rsi uUY kjkrez jizu ef sewoqhofuj ub kzo gqifef jewo.
Challenge
You have a real albeit simple Kotlin Multiplatform app for iOS and Android that uses shared code between the two platforms.
Saov zcaksojvi dew choh wbijcow uq wu exm kvo eER bvnyinLipqaek imwi qxo pqoomopv id hxi iEY osg. Ad u qacx, puu dik uja OUTizaxo.kiqbittJufeke.wvxpurJommeiv ri ucbiez xpo hzfcuc quzwauy.
Slugi ote xme ljidrq xa vakhijur hmen lewxorw or gdah qsursawqo:
Zwufu pu nuo your be apl pyil jijo fi fcaw kdu kzcdid vitsooq?
Pa yuu coam fa diqaoyl nve mnigoq moki penive linbuzk cxa uAJ aty?
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.
Tne Habfaz Baxdoxgoxsezk woylihozs ip yirn nirnegf vpugwos, ku pcamo’g i xloal ixqexnehihj fuf mo tunxsivihu ka mfo KTG iquxhcmev.
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.