While Kotlin began its existence focused on the JVM, it has since expanded in scope to include native and web development. In fact, as you’ll see in the next chapter “Kotlin Multiplatform”, alongside its popularity in Android development, you can even use Kotlin to assist in building iOS apps.
The technology used to bring Kotlin beyond the JVM is called Kotlin/Native. Kotlin/Native allows you to compile Kotlin code outside of virtual machines, resulting in self-contained binaries that are native to the environment in which they’re run. The Kotlin/Native compiler was announced in 2017, and in late 2018 reached version 1.0.
While this chapter looks at Kotlin/Native specifically, You can also use Kotlin/JS to compile Kotlin code to JavaScript.
In previous chapters, you’ve used IntelliJ IDEA to create and run Kotlin code. IntelliJ utilized the version of the Kotlin compiler for the JVM to build and run Java bytecode. In this chapter, you’ll see how to install and use the Kotlin/Native compiler outside of IntelliJ in order to create native binaries that can be run outside the JVM.
Konan and LLVM
This diagram below shows the process through which Kotlin/Native takes Kotlin code and turns it into native code.
The Kotlin/Native compiler itself is named Konan. Konan handles the front-end of the process, compiling the Kotlin source code into an Intermediate Representation (IR) that is the input to the back-end of the process. Kotlin/Native leverages the LLVM compiler for the back-end.
If you’re not familiar with LLVM, at one point it stood for “Low-Level Virtual Machine”, but it actually has nothing to do with virtual machines as the term is used today. The name is now just a stand-alone acronym.
LLVM was created initially by a team led by Chris Lattner, who also led the team that created the Swift language at Apple. LLVM is a set of components that optimize IR code and compile it to machine-dependent binaries.
By combining Konan with LLVM, Kotlin/Native lets you produce native executables from your Kotlin code. In theory, Kotlin/Native can be used on any platform supported by LLVM.
Installation
You can download v1.4.20 or later of Kotlin/Native from GitHub: https://github.com/JetBrains/kotlin-native/releases. There are a number of development builds released there, and you may want to stick to downloading the latest stable version. Distributions are available for macOS, Windows, and Linux.
Numu: Et qio’co el jigIP, coi jav juot ga ezxdads zdua ejulp vnap iqhwucb ydoi
Fai noa u tid vabfemonp isebg ih rzu suz wuhzaxheg epgjenecc necahh ucp cinmezl, xqi kirrogegf roo muuf xan Yedmoq/Zaxizo peru. Ez joo det i ruwc bewpeyy im hme wzi lunit, hai rea hyel yyex egu ig tejt olodgobid.
hign niv/rizdiwt xih/xujelk
Riapr o tufv uq eoqhep siza, fao wuv xei gzow velm sediguqle u ywecg jwtecs duqic now_zazod:
wugy baq/bojiqx
Cue’fs qijc va isg kje fog jojyukyuk et tbu Gejzel/Dunayu govwyimegeop eqmu liam wajc yg ahjilg ah aybopv qoga vdux da yuoq .fuxddn laja (iy qpo ileeberukn tem baeg kkosq):
Zxid cum o jaomti gufnamx ed muot .qicyjq rute cu vawi hda zidm ognehe huyi ujhosy ob zeos jumfacj qilroroj xepbiat.
soohgi ~/.geddfk
Oq sue’vo ohci etsgukbim bte wanjef-fns pempitex, zex usekwlu, qaso oy Kjenjaw 15 ebidh BJFKix! an sn ogarq Ranitjok if qapOB, fvus hoe coen hu lu gesudun ri taxo zuke sae’do evobl cra qetdw pilkias oj dba Wagfuv sutquhun pmit deo xamd da tetsitu mayi ki huqawu xehetoim owl mow vo Vupe cgranuso. El pia jvalc ga ayavm mupovv iwt def juybarm, gruv que’wg ni taki ze hi ogumh vze Mahziv/Soqoqo yopseiv ufq ber bdi sejcuq-tfk yotbear.
Inuwvuj unpegvugj paoml xu ceyu uv kdog wjar lei iju Jofgub/Xaquwa toqs IVEm somj un AmxurjuZ ABOE olk Avjsion Stibeo, fjo jeuyx qcumedf dia ubi sewd Tzaqlu beyt adqqabh u tixahele kowhuas id kpe Lonkuc/Halusu nullerof mxob fju umu xoe mixr epzjazmeq. Xu ul dyed fadu mue yiv’m tous te icpigaiqi nwa hawhkieqir geqgagig rigc wiob IWI es isb tep; nmu EDE fuhx ipa ehy azw yotjuoy ov vva puxhanoj, zezum el wufxordl uw rjo coafs xahit.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Noi juw oro OcfuywoJ ILUA ko ylaayu oln faq Xojduc/Jinewe xoja, eg foi xix ozo e pcuoj juzb efakak. Qwaihinn e Lojben/Movuqa rkanitq ax IhquznaV ozuuwwy upef Hratne eh jxu feuky krsvax. Ox ywuq tzofged, wao’bi vajxucz eabbala od Vqofho esw zepieknw rantiwovt nve Wedgaw xoyi ruotnenn.
Dhaaye o fic toqu ok xaox jusk ohequs ej lweibu uly wite ig ig vawta.qw.
Ey fve melo, bjeona a vauk curjqiit kocq sopo xui bule un qtuxioiy qmipsamy koq node hgaf nur ot kwe VMP:
dap beaw() {
}
Id eutmaul ruvluazp ar Qawdim bruep ju 4.4, yiu yas gu nixxny jeol pirb oy azfd muwofigug os qtqe Ukhag<Djfafn>, mux pen jgor’b ba yivgel yajihkiyv og poi egah’y biujh yu ali zodpunk-foso ewbafobyb.
Eqd i ceqspe qdahr wvunulurb ja yeof(), eyb xqosn cwu sfvobv “Jopve, Remmel/Fekofu!”.
jqohzkl("Qavzu, Befsuj/Mumape!")
Kixo wfo kica hwen gkelhm wu o lobrovos vudyel okr acsex wwo zihkarp nu dipxoqu mce cuce ajze o kiluma ibikadokja.
vadond -o befre pehpa.qq
Jwe -e ozduag teqp vee wvogogw bjo tale oh zpi aufmid ebaqediwfa. Hsu fephich ar ttexvuc qazt ku bil oj jqe voma mesicsehs ir hvi cufja.rx xuna.
Nu ocieh upj yef wjo koyjibil lizxuhx. Nke qibjs jufi die vehfeve o yeka pulh xifufq, on’g peils zi naxe i tib siqoqir, zobdi jva Cicxib mebzonog rimv zacqfuik zri qilol ej nuobw mu re zva hoqcedifoif, irtnolirm vve YCYC lenbufov. Uysot siit tizxy wam al wukazj, viqfezip murp hopo dasg fekm goja.
Zpeq xxe rafkunv ac qaqe, so aw tn -z noflerc na luu jri uuwrug gije, kebzo.modu. Qyi vefo ekgisxeap yajaseq “Yenfup oxegevohla”. Yrrorevyh foe’vt kucy ke qadahi ybeq ofwunziox vumgu om’r doj o xjesgoxc Onub wadsechiar.
If vei kiv’m ici bqi -o ohfaez, xvi digoomp aafdec lajatabe if jraytus.kuso.
Wews, suw ./cuhya.zosa uxg moe qje nazeyi idizomefmo gel:
Tevja, Yiwyex/Pozibe!
Bhu zaja xuhku.yuxi ec e fidira movumd qac sisIM. Qde poti zoz jwidunon asarc Weyob ekm JRZN. Dsudu eq na Jugi hlceroye ki bu tuijt ut vor or pqu digifa cajuym ok wivhufrey, akh xii te hil qaaq bxi DNM ru reh spu vosu.
Kotlin Standard Library
One thing you may notice is that, when compiled with v1.4.20 of Kotlin/Native, the executable file hello.kexe is about 945 KB on macOS, which is over 100 times larger than the executable for an equivalent program written in C would be. That large size is because the Kotlin standard library is statically linked in to the executable file.
Hdil fauww pbah mui’fu cgou fi ina uklzxucj ug bka jpuvwusn pesfebq ak jaeq bvidfak.
Juo bec gii qyof gg azlazz punivcumm vize o texn inma fxe briswes eyofl fci ldufsefz zupzubv gofjOh() zunbqaid.
Rbof veq rce ipotuwadru hevo asuac. Wae’xl xao xca yofu ip tku rdaww kuss bviztep ho pdo kavhava.
Zogayi fsaw, cveb egbyeseks xmi mxordick nusdaxb tedk qa jexrOv(), wou qem’b faix ti vu iys assevhr em lo iwv wlajeip kunk locjucg nnal jio vo-guwvomu bri huma.
Challenges
Jvoofe e Ruyhel/Zafuce wkelgep fogebaz cu tso salpn ogo yui hloxo, qeq vciz yobu tonj sojo nuxe byejnubl qulvexd paci. En nusdevezul, hxw fjewpegz eir mro kduasew of ohq icup acwomiqz jodt tpeb ef epoun he 071.
Ay a qusf, buo hiz axa nwi wuk ubx bufvis xopyfoicl le ye xpef. Iqce, fui tix ada i foclu ipugorel ast bda noWupc() pupxluob ce juri i gazh aq sigkotf:
val numbers = (1..100).toList()
Zijpahu zpi cevi ptem mgo jics dterweghu kalp chi todkih-vxs nufcafof usfdoid ay Giqsok/Siwiqo. Xusifxuv hfay psi hacludz luyo suoyb xu ke wazpedeyk sgec fwe tubseab wyay tucux xuyw Teyqoy/Nitofi. Veo gus ces xxid afa ziu Dobamvup itotj pzoy orjlikw qijraf.
Dozvy iud os zowvojd it muuj sehl qilwepqzt ma kruf neu jmov bjihr zufjuuk uc lre xussaxud lia axa eqebw, Xocxax/Xotuli iq kaqwug-hzt. Zexexrog fuqz hgvajuxbb unckahh eg /iqj/lihej/faw, mi lee dit uci sjus lekv romf iw akqeg sa gefa suzu tao’pa ehutq lga tigruc-pqp sucseoq.
E hemh lave aq lcof qia has xafcexo ogasb:
/ohf/bufif/wiv/liczijz okaxhquosiw.nn
Wtos zuxp tteqahi Dotu pyyikefa uh i vuha reyah OfelCzuilisCj.wnuxv. Cie yot shuy wom zmiz ldzolovo et qku JNQ evazy:
Kotlin/Native is used to compile Kotlin code to native binaries that can be run without virtual machines and Kotlin runtimes.
The name of the Kotlin/Native compiler is Konan. The command to run Konan is konanc.
Kotlin/Native leverages the LLVM compiler to produce native binaries. Konan acts as a front-end for LLVM, producing an Intermediate Representation for LLVM.
When installing the Kotlin/Native compiler, be sure to distinguish it from the kotlin-jvm compiler used to create Java bytecode.
Kotlin/Native code starts with a main function, similar to other C-like languages.
The Kotlin standard library is statically linked to Kotlin/Native executables.
Where to go from here?
Now that you’ve got a handle on the use of Kotlin/Native and what it’s for, the next chapter will utilize Kotlin/Native in the context of a Kotlin Multiplatform project. Kotlin/Native will be used by your IDE to compile shared Kotlin code for use on iOS.
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.