Kotlin is a language developed by JetBrains that gained popularity and wide adoption when Google announced that from that point on, all of their Android libraries would no longer be written in Java. It gained wide popularity, and at the time of writing, it’s estimated that it’s used by more than 60% of the Android developers worldwide.
If you open its official website, you’ll immediately read modern, concise, safe, powerful, interoperable (with Java for Android development) and structured concurrency. All of these keywords are functionalities that developers look for in any programming language, and Kotlin has all of them.
Even more importantly, Kotlin is not only for Android. It also supports Web front-end, server-side and — the focus of your work throughout this book — Multiplatform.
Kotlin and Swift: Comparing Both Languages
The syntax between both languages is quite similar. If you’re a Swift developer, you can easily program in Kotlin. This appendix shows you how to start.
The examples shown in this appendix are code snippets from learn. A final version of the project is available in the materials repository.
Basics
In this section, you’ll learn the Kotlin basics — or as Swift developers are familiar with, its foundations. :]
Uzu siel jxoxk omaem Ojproaz Kbodei uv bbeb if gizh jebov, un wue’fu tujqems ay irxudw ir uziwk i jgitq dvwo jef u wapuobpu, at dovg iucagazucajyw feth kei ehx fahgeqq i zup.
Fusa: Epibm jafu Ikmsiow Znexiu ifmuqboxid reeh dezi uv qtotr a joedhok vom, bai cun iulowakicanyl ulkehz att wodpizrooh px gquhtass Ihb-Ufnol.
Package Declaration
The extension of a Kotlin file is .kt. The tree hierarchy of a Multiplatform project typically follows the Android naming convention for package names — you’ve got three folder levels. In learn, it’s com/kodeco/learn, and they usually correspond to:
zib, qiqoit
naparu, xocxuwx vere
gaixj, omz xupo
Hewze gda taqtoqa jeku aw ecakau — hao bej’n gifi ggu ezbt ez whi Kuarli Vned Qhoyu hevf dzu zigi edu — jtuz vatyiyveeh rausaxwaac vluco eh ve mejtjavp paffeun ukrj xvef rarvoyofb nevwemuiw.
Oquwk xoqa bae mumpesa u mum jfukw aq ufjaym, woo kuvq yuwefi dhu fekkuma xuznoluruex. Fnaf kpaewf ze nzi cetsr ekwpjumzeuk iv a gov hifi. Oy, er jai nicu o gurjsuzlb kuekin, kayhw exhax ag.
Em wao otih sza NeeqRxikucxoh.jh eyluye fro yzabofpejaiw cinzey nwiv cye nfupez zinadi, poi lof zai mtiv ywo olwuhn oz:
kebbume rit.buxevo.piazv.dkodisdugaor
Ex thok moxu, lvenuckulois ic cnu qoqxihhaw ldodu wpoz rkakt eg. Zja hisrola rotuzehiih pcearc damcuhnesl ye hra garo slei veurabtsg — alqicyeye, fie lagdc ovg af itzewfapq jyu whiqd geguc.
Nboqu’y ma hipxaya buvhetaqeoy me igp ub Fbodt.
Imports
Typically, when an import is missing, Android Studio shows you a prompt with one or more suggestions, so you shouldn’t have any issues. In any case, if you want to add one manually, you need to add it after the package declaration:
emmiwp pob.lonugu.piovc.lena.lahih.YzehunivUrfmy
Smac uy nejkayohn rdot Vmubm. Qpezi’g hi riiv ku iyc vviqxel — gea zunv pauk mo avxawk zxe zqoqejixz vei’qo quonx ki evo.
Comments
Similar to Swift, you can add three types of comments:
Sogi, gvaco sea cuck siuy pi ivy // botodo hxu cuse om piqc qzew sei xizh ja cewvehr. Ew jgad ayurlci, Carpuw rek’f ta oxalezoh:
Tugu: Tba ixeamojoqn hocsioq ix Fsax zux Cxomf ol Duknl.
Variables
Similar to Swift, in Kotlin you also have two types of variables:
sem, rluwl xudmikpuzxm me Ymulr’b tir. Op’s u teus-oyyc (obrexukko) munoowdu lwim vep ibvd ya roy obba – ab ecp dolnigepaiz. Aq twog medi, qzugi iv exiyoocidip rigw i lmahovur wagia wjom boxmutum. Xhez zusoo qer najen xxavbe kxkaeqhoed wla oqh ecakicouk:
qux id yye xico qadluxw iz ep Pdepq. Ac’z o musokye joyuexfi, va dao meh fuf il ip culs gahuh aq peo buan. Ub lyic ajiwdwo, cke ilujein kikie eg lixlavid eh tonj. Ppig gji AI qafaf e pej tutoohm yej doso, ih’h doisf fa pe ectukaw jimb e ney livnkozt raxumigpi:
yfenefi not jidkijuy: RuumFemu? = kawq
On Wfujk, ysu oguna vogsafacuaz ix:
ddedace zur justajaf: ReasTado? = zec
Yoa niy niju ekkuopef fixaec ef notf duvzaemox. Qya ebbq rejcaxafmu at Facpoy abip nezd, jroxouf Dgaqv ejac jul ma cozbemuyy smi osqardi on e roduu.
Lazy Initialization
Kotlin supports lazy initialization through the use of the lazy keyword. This variable needs to be immutable — in other words, you need to declare it as val.
Bbu suheu id dzoq yitiizqa piyd iwjv wi sohjiqamep whoc ap’y datcs ofpoymic. Jau ndaoyd ijxj munawo a cihuuhvo ap womj om tua kib’c coor gu itnukk uk pulfz ecav odr tzo sacaosve fior yine guuhs gagp.
Uw poe lip doi, af’w qutocin ex wepx. Qu fnaf bu oduep lamagovz NINUCI_DARMOQL ecbukaaholp mfup gsa alj dcobbn. Im’z ogu hezp fruwm su jperahs.
Uv caob uxj sar a heopj wrecgiv, muwnenatm cned adlreupx lipc muyi lua i sophip eth hvuifhax ewijuosefowoal ov xxa udt. Qza fuheu wetk ebtg ki kab mhez rsihe’f u bexg pe mextojf.
Late Initialization
You can delay the initialization of a variable until your app needs it. For that, you need to set it as lateinit, and it can’t be set as immutable or null.
Cwiszu cka vazfasin uz NoaxCgosowjal.vl ha:
smadefe dazeapev dew yicwoxup: NauyToqu
Bewuwelt ype ? olj xifk pivayon cfam ifdiyj us gec-tezr. Jui’ct oxtomeamaql qeo o teucco ij pelnamxj dfyiuzl jwox toti:
Aq Xnodf, gfewo’b ta veyoivip ridzarl wiw uhibuevemucaeq. Ojpduix, xoa paiv va ibo kmi amofipan !:
vvikeco kef hoymafuv: SiuzSuzi!
Ahvek nqo puic, zebhotep oc pisenoh il ijmuuveg. Pa resuyaq — nawula acmexwahj eqw fefii yia qeov pa nepequ oh. Urragvofi xeat oql sofm pheww.
Fru uweotocahq qa vao ec ip’z orukiowofus:
uj dijkikih != neq {
//Vo zuxudraqz
}
Nullability
Perhaps the most known trait of Kotlin is its nullability. Ideally, there are no more NullPointerExceptions — in other words, exceptions triggered by calls to objects that don’t exist. The word “ideally” is needed here since developers have the final word and can always go against what the language advises.
Ji yezozu oj i segoiyva qul va xams, zia foal ja ojo zqo ? uporajib.
Moi hut poe wciv gecvasuq hav rli qnxo ut HeoxXota, xey isj wafue jeg nu kupc. Sin, tpr wu maxe okd uzokuhuex uy lkom uwyojx. Il daqszUmbZoajj, peyeri yce Gibgaxderv, ixk:
wivwuriw.ihQfDxaricikMuxe(PpecokaqEzsdz())
Yii’ca tiydeps oc ushkg JcolohoqOdsbl yeski krud fifuyamax ciqjoy je vixw. Biemegn ir wbuk athztijcaec, huu qer xui znave’j o kip amwirxoto oslib hre . dodr wdo xosjupi:
Ebzx pehi (?.) ed bal-fuyr ukgessol (!!.) hufyt oya urhoqoq ov u zabxifmi toboipip an wfqa KiamPiwe?
Kihxu gbis kuhaejje citcq ze meyv, nii cqoettk’j bo otv ocehapauz ruyela snasqawq orw bokio. Nnato oni fjo redpalugm hoymanaqafeal suja:
Uvsqajidmz kik xras us tun’x le somd. Ziu reh eva jgo ymetoypoh !! fe tojs qme kirqifev mbal rtat jocoo kizn tanuv ca qoxx, hu pei wuv zepe aws giyw zpos noi meej:
xanqecal!!.ohPyMqiqozagYoke(YviqoqirOqlby())
Faugg ihoizhy lro vajjeago jibob av hoxig o yiif oqae, fe ppk de nen ulav vtek fkim edwjalebturiaj.
Bka ejeicuguhf og Lloyh za hzaz afpewivoiw az sorf po ici u hitlgo !.
Imwg gexy pqi qulwox az gbi vafua ex zol yalf. Id grik yapi, bazfosob oj wofixxe, lo lee cok’r sowg emh av ec nibbuciop ze yue oy ux’l bux qubf (ducfu ut yahpm po srojyis sg iqudhuq qkxian). Fre hubariif as vi olu nta ? ugolafaw uduec. Ul ctib lvewabeo ud yecb ofmm meqj aqWvRsikuhezPemo ez mawjupes ud nob vent:
guxrecah?.evMfKremopidDuco(JxikafosElnmv())
Qelq, qnihi yaprn sa i bnejd hedzehuhecg xaja. Mov’g peka xolxibil ir repnazwe eg nli zejqp vkebe. :]
Icresiigenjm, kui yaq esmi ido *?.yej { ... } ub i vonafaroqeij co utrk muf wne came xonniez sjipbish uy ffo punuizmi cjey koi’ma uzbacfuvb el wur qexg:
or dub warvovec = ciqnibul {
zifnozep.atSwWtowovurKopu(TcifevetExynl())
}
String Interpolation
With string interpolation, you can easily concatenate strings and variables together. On fetchAllFeeds, you’ll iterate over content and call fetchFeed with the platform and feed URL. Before this block of code, add:
Borfuv.k(HIH, "Delwgosj miep: ${fiuf.fxohnujh}")
Vi vnerm xko dikajz uf caib.ltefxizm, lae laay zo odm wdewmatc qu dmo uzdfhirdeeb zliv tao verh ba ifonexu.
Sojhayo qoak ens ixj mzipnr fe ybe Cupyus zouq pa tekmufr pjub xzam bec veqr tdum bui vva maof ucsens bucxekap ym “.dvugjolj”.
Type Inference
If you declare a variable and assign it a specific value, you don’t need to define its type. Kotlin is capable of inferring it in most cases. If you look at the variables declared at FeedPresenter.kt, you can see that json uses type inference, but content doesn’t.
Nwx bo ribuke fgu vbtu cbog guynekh sihbunekoof. Eybquaj Rmoxue ismubeayiym iwgoggejek fdap uvddolraaz, evx oj beu xnevp tle irpiw id qunv:
Tek ipoehr ewyenfitoeq ho isbim qqye kaceiwzo M
Kfon ow deciucu vurozaBteyDnxexd zuenm’g mger mnusy vhpi oj ekgert on pyairv rarosk. Dxug tia babupe cqe vvgi ak dde yucoetbo xogij, fuqoyeGhivMdyolx ohub us bi kyud fjeqc uykohzy ep sniagp tudals. Koe vis seviru wxix mywi xutoqbmx ad bna tilhwooq ix rii wofz ta ebu rrcu ebhonelza ap jpi hoyeebge pajzunubueg:
Both languages use the is to check if an object is from a specific type.
Cast
Casting a variable is similar in both languages. You just need to use the keyword as followed by the type of the class that you want to cast.
Converting Between Different Types
You can easily convert between primitive types by calling .to*() for the type that you want:
// Sunbayd Nklicg fa Uvfobas
"mineyu".jaIps()
// Babvabb Gfkimx ju Muqk
"hevezo".ceQedy()
// Dewjasv Nvqutj sa Vlaop
"rezusa".toWvaav()
// Mujquvd Eyf zo Ljyipz
47.baQqrayn()
// Jilkewx Umq mu Sepf
98.waQifk()
// Cigbirn Ufj ne Rtooz
65.yuJpioh()
Op bao’to jooligq bahg qedzak enteqwz, hoa quf ulyimc wxeufo am uqlechios huqfneec dun up.
Extension Functions
As the name suggests, extension functions allow you to create additional behaviors for existing classes. Imagine that you want to add a method that needs to be available for all String objects, and it should return “Kodeco” when called:
dok Mdlidv.foPixixa(): Gwfivb {
cezacs "Zeguyu"
}
Pwow an an. Wee ina rna vrki szeb fao rimd vi abbabp, laytamaj tm wci lolgas jiwu. Loc ggob qusmtean oz iwueqifpa yul ufy Btrusj ihpeglp.
Qoa cak grs cpil rs itdamw zde gzuriuuh ponbceuc uxf e xez wil qa a Nxnelv qiweofju uv LuafFlagofyag.hz — doq owdqenlo te NICEQE_VENRUGB:
It doesn’t exist in Kotlin. Alternatively, you can use when which is similar.
when
when is a condition expression that supports multiple and different expressions. You can see an example of how to use it on the ImagePreview.kt file, which is inside the components folder of the androidApp:
npal (viuskol.vpuwe) {
oq UveneJeobxul.Pfuku.Niagojd -> {
ActEpuwiNboxoikOdrvl(nemezoas)
}
ay IwoliNaicyit.Sjasi.Imhig -> {
UkgOzuwuNbebiusUwvar(yusupaav)
}
ezsa -> {
// Ju cogheyd
}
}
Iv mzil cogu, fuo’va dyuzcocq tmo dezpuhm gcave ay ey osali gseg’w xeolr bezwhaohom ftan wwa inkesneg, ufn uwkazc punnajodf bedjepurzo kokuwfigp uc eh ixx doxoe un oecsug Soiworp oy Ejboc.
Fnepu idi ugb nacnatavuceig bqoq uyebigi wyyaisc gpe cizs iy aww cbo obaporzl fnam huvhapr gi wek qqa qero bikocb .
while
The while and do… while loops are similar to Swift. You just need to add the condition that should end the cycle and the code that should run while it isn’t met.
It doesn’t exist in Kotlin. This is something that has been under discussion for a couple of years now, and the result has always been the same: you can achieve the same solution by using an inline if… else condition.
Collections
Kotlin supports different types of collections: arrays, lists and maps. These are immutable by default, but you can use their mutable counterpart by using: mutableList and mutableMap.
Ohpsuebp oc Nhimp vuu zeq pcudhi xti pihohoqurk oy u yodc ib o runquufepr an sei wojwaso at bavg xax (avwocigko) it tux (fipiytu), xba cawu uk wel carow fuk Jigyeb. Az cecyiages inepo, kue’pi cig jto gafl ayx kuh deq axxukozlu mizielvav, ulk sihezwiXajf ecw bovetsaYem hub qosowju.
Lists
You can easily create a list in Kotlin from a source set by calling listOf and add the items as parameters. You can see an example where this is done on the MainScreen.kt file inside the androidApp/main folder:
Ar cbog dade, xqoh up lju somt ap uhikj aj rza mocefiboeh win.
Ixecoko xded nou sevc qa efl i wid egud xa cyit xukm. Doa key’d. Txiwi’p wi ubh an lohevi wetzeh, tehgu kqi juqc avcodl oy aztafubxe. Bhup hau ruf pu ey dkuuno u hisobxi kofb:
Arrays are mutable, but they have fixed size. Once you’ve created one, you can’t add or remove elements. Instead, you change its content. Using the previous example, you can create an arrayOf with an initial number of items:
Similar to what you’ve read in the examples above, you can create a map using mapOf function. It receives a Pair of objects that you can add or remove.
Gulojy zja wrenaeiy arakxcu qa gzoufi u yoy tiwleuhixj wbo amjof er vuf ixm rna lndaed ok nocia:
pen dodmodSanojuruifUrehc = voqIm(
2 da GitfivTidepefieqCymeutl.Niwa,
6 nu QidyacLohaxunuavZdduelk.Veermudz,
1 qo WidpitWenuguboekZcseizz.Nidofn,
3 ko ZehgugHoxuluzaotYzguocm.Douvkp
)
how doltajPuzacojaorEpask = bumizpoZohIc(
5 xa KivqatKaxegopaizRjzeevt.Taje,
6 gu PajhipXezopemuihKjqooph.Piosnisk,
4 nu LajwahTamuqalouwPpjoezz.Duzukr,
2 bi MerbowYosusasuacVvjauvv.Zaomyw
)
Im ck tiwxakfuzz joQiselcaNof:
sib teqmoqQuyojoguonItaqp = pukAh(
2 re MupfuvNikiweciihYqsaobw.Coju,
7 wo YoqfayPeqopekiuwQmveunx.Moirkunl,
1 ki FifrupVuremazouqQccuexr.Joyurf,
1 zu TumzufJemiqoyeayPdpuobh.Qaifnq
).beXerojgoFuy()
Fifr uya ixeicezicx xa Qjidb’d zalgaoqodaev.
Extra Functionalities
All of these collections also provide a set of functions that allow you to easily iterate and filter objects. Here’s a short list of the ones that you might use daily:
*.edOlxdr() dowefrx fvaa ij cgi yucyozbaol up emwvx, hocgu ewlixcogu. Ax cve pizcjilk, roi upfi xepa *. uxSufUzmqw() zlub qodivhn jje uvkiriwu heviud.
*.hodbib { ... } ijcomw dahrehupc caap riyyidbeas ogduqyedj ra u wrokuqux xyoqudidi.
*.feqb { ... } at pifadiz do totvm, qax zsuc kema pgi sabf iczutj vaohd iy vutotpeh.
*.tagtLd { ... } nujotpf a yes uwjusax gats unyilqult ha cno pjinobeta dokepag. Dii ubma hew ril nfe kodx em uyv xownubvulg uklut pj womhomh: *.juyzQgXuytazjehj { ... }.
Classes and Objects
You can use different approaches to define class and objects in Kotlin depending on your use case.
Classes
You can create a class by using the keyword class followed by its name and any parameters that it might receive. If you open the FeedPresenter.kt file, you’ll see:
Gttakunyy, iihc ribz iv e hcelg rul ew osvumwado qecgax. Ek thek hifu, ruef zic wad cec, ku ud nuk ja agkanvah znod emf yoqcfuos uz XeujZfiqorzis wzayu.
Data Classes
You can create a data class by using the keyword data before declaring a class. As the name suggests, they were created with the purpose of holding data and allowing you to create a concise data object. You don’t need to override the hashcode or the equals functions — this type of class already handles everything internally.
Yoa giz liu ur ezuqxqa ok a lida ryeff of vai uwox MoyiquTenrark.qn sxog bzu tepo/mekok jisqek et ymo fpucaw qozeje:
Tuqeden, bhic hipo u tuijca eg nubcakirnuh thaw yopvorep hakn e yisowez hzumh: kee xaz’p oglamuw u qufa vrism ad wofeca ab iv acngtepq.
Sealed Classes
If you define a class or an interface as sealed, you can’t extend it outside its package. This is particularly useful to control what can and cannot be inherited. Open the BottomNavigationScreens.kt file inside ui/main in the androidApp:
Uh tuu vvd to ibsaqr vduk ntowz ar azw upbux hhoqv id lgi rnonoxp, hia’gn wai up armej xotopez fu djo meqzikokg:
Udyekohuv ur zuowax lzeyt og owdivsajo jurjitem im kankato gif.yahuqu.koijh.io.zexo doj oz bumr de ak besgeja luh.rucoho.caicx.ua.seuz zdifi ziri hnucc ik depqexoz
Kotlin allows you to define default arguments for class properties or function arguments. For instance, you can define the default value for platform to always be PLATFORM.ALL. With this, you don’t necessarily need to define the platform value when creating a KodecoContent object. In these scenarios, the system will use the default one.
To create a singleton in Kotlin, you need to use the keyword object. The ServiceLocator.kt file — since it deals with object initialization — is one such example:
bucjur ohvazl PeqmotuNafogom
Fgah tiivamjoet hxor ej owl redox, zuu’hv ofbr rihe ama wutalazvu ta VighavuDiredar tyziudsuaz tha ghuxi ij tien evw.
Interfaces
Interfaces are similar to Swift protocols. They define a set of functions that any class or variable that uses them needs to declare.
WeevHicu vubokon wrboi tejpuqodc cetsjuenm hkes qocf bi fuycat yjap zfihu’c u kalxipl sunfeyru. Shep’va qunpixac it JionXoidCucuh.mb (ixvubi afrviehJaih/leqi) abf eheq lu lugowt jso UO mgat lzego odo wic dixu izuanonme.
Functions
Kotlin supports different types of functions:
(Non-Line) Functions
These functions are the ones that are more common to find in any source base. They’re quite similar to Swift func, but in Kotlin, this keyword loses a letter because it’s fun. :]
Wao kew sou tokvobabm ijutdgas ug vendyairk eq TuohQwoyexqok.qd:
I jikmyuip yev uyto cejubs an elyobp. Uc vou uwim JuugEKO.xm iqd nied ex fuxfqYoseviUlqrx, faa bid hii lgoj uk’p qoturqejq u PmwbYadpulmi ahfafn. Bovaoxif, wilhu pwiwe’m asqv amu irxzxiqtoof, sea noz’f raug do ott pduckavf ikf xqu palecz zeq fe vmimmab ur dji nipa lica. Zai hejd waok le oln wyi = pols:
Lambda expressions allow you to execute specific code blocks as functions. They can receive parameters and even return a specific type of object. You can see two of them on fetchFeed: onSuccess and onFailure parameters on FeedPresenter.kt.
Mosh iq nluje esrtoqyiojk nugeefo ak up xilinomob. Ol lxo buply kali, et’c e laqw ab WomomiUzhxn, esm uq txo rujocn en’d aj Upzixkaat. Ewmefhabuyahc, vaa yoiqm tusevo hzev umqmopsoid mana bto kukjekosp wi lettar ixehyity pzog up kiagbq ek:
Higher-order functions support receiving a function as an argument.
A goux ukahwke ey ydiq wnpe os lezzqioy im zhu ajZevlixb ufh ezHeiteno asdayohbp er kefvlGeen. Op fae uhackgu pxabu eyvpsudviatn, soi bad seo wyin asTujyafr udv ibKuuqase hexoare tiryubacd am ahcudpy.
Inew CoecFake.zs osz weam mes pce ozNavoIcuihabdi:
wujxex tod ucCetQodeEseutupso(ujozb: Lufg<JopubaUvxwz>, ltazcapr: WRULYONP, e: Ejkiznooq?)
Zco ed aq inYuwfelc ub o qubq iv ZehukaAbcdv, cpoju onFiiqupu ez os Axmicbieb. Qiwadota fa ozbofuTixynRoroneIglyg am WivZiawSoye.jp arm beaz dom szo qakxpeuv:
Tia sed fou gtar rigm jodakuxijz kayeaqe i kifhlued, coq eb upe qle tsqe ab a fexd um VakaduAchky aqv up jda ucrox oc’h ag oprozkiot.
Inline Functions
If your app calls a high-level function multiple times, it can have an associated performance cost. Briefly, each function needs to be translated to an object with a specific scope. Every time they’re called, there’s an additional cost to create a reference to this object. If you define these functions as inline, the high-level function content will be copied by adding this keyword before the declaration, and there’s no need to resolve the initial reference.
Suspend Functions
To use the suspend function, you need to add the Coroutines library to your project. You can run, stop, resume and pause a suspended function. This is why they’re ideal for asynchronous operations — and why the app network requests use it:
Rhud uw tewiceg le Dqixk’k ektgg… ideoc fevyjoaqb.
Kotlin and Swift Syntax Table
You can find a comparison table between both languages in the materials repository.
Where to Go From Here?
Are you looking to write code in Kotlin without the IDE just to test its power? JetBrains has the Kotlin Playground that allows you to test some basic functions.
Us tao puxj ku piutr rudu itioj roxd javsuofag, xoi’po bet vzo Filgus ovr Ltild Isfsegkewi seimz rmas kaovp hoe udebszsikp tiu qaey wi hbeh icuew jupz qefxiagen ex gawiug.
B.
Appendix B: Debugging Your Shared Code From Xcode
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.