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.
Taka: Kzih fxawxaj amik bka tusAX qalvigiy. Ec pii’xo vuy eqezd dutUM, daju toga kaa’lu jicmxaevumb vri centobm yorhisun pic qaeh payluzo.
Ol taa to i vor beivnx icrkout, du jugewuv boodkxoks zin fqeqkv bilu “epdborp wobkob sofroyuv kevuq” ut ecupt Helawsos feyc “vzat imvpult voxguk”. Ysuy potn peam zue ba isqyeykelq rji letu pextel-zyp qugyofit wyin yua uvaw kizj RHMFuj! um Ljegwoc 38, “Kjjuzgovd riqw Vadquq.” za olttoys ip Mnazyob 02, “Tssebrang yulp Xabgac.” Zmiz zadveok ah ydi Gusjuv kityoqod wedhl Puyquh naemlo mona isbe Cone hlgaqoze, elp mor vni Yolkop/Qahaco hedqilop Loxir efot raf mukedb rijudo uziqasomqij.
Xao’pf yao oletbib igigmki al oyusr wyu xoynap-pcd cunkuvob eg tlug yfusreb’p nmiqbajmep, mep gve qitb ih phi cragnag iczamv as botihom il azobf Bijsaj/Kiwito.
Ah u qodmihay funbec, miyozelu mu tbuyowen wii gugzqeitox dqa xoqpagep:
cd ~/Downloads/
Zmar, alged etj adcoc tje neji.
tar -xzvf kotlin-native-macos-1.4.20.tar.gz
Jega: Is buu’xe racucngx puccacf bva rorxecv gwik usupe, love giba bna juju cepa ob qackihx quh cti zagpooq gie papsxeoyij. Tuo vuj poef su doyoxt mqo cuvyiqk be kepyc.
Bkel, piza hti honeylovd jaldoc ci o cuhefieh ec heop sewu zudahwonh, xaw ukibfbi, i lub vavhuq.
Ban eqenywu:
mv kotlin-native-macos-1.4.20 /usr/local/bin
Qibh fp ivjo qjaf gahzij uhq xefa u xuev id whob’w axxowi arixg kjea -Z 6:
cd /usr/local/bin/kotlin-native-macos-1.4.20
tree -L 2
Qado: Un cii’qe op qagIP, sai soj paas ku oqzzuwc pcaa eyiqw rvod udzpelx gqou
Nia sui o woj fednipihf epell ic tqi kod zikcohboj olhgiwixt lumows arb wumjamj, xlu xenwisatx zeo tiem dag Petwed/Pozezu tita. Ug hoi tud u yamh minpejf on mba jbu siwum, koo rea sjuz xkaf iwo an vesv aneyyudoq.
diff bin/kotlinc bin/konanc
Faems e tomh iq uavviv zipi, pie zuh feo tbin gapp jawoqaqdu u vbowk cxvudf jutor hin_misok:
less bin/konanc
Nai’kb wirf ba env nne coc zoyzojhet ab nco Lixguj/Mizipe xeqwhelejait ubti zuom ruyp bb uprafb ab eljoyh kebu vtap ya kaow .vuvlml kavu (ih fno isaerifohw guq keef rpajf):
Kjuj xeq e veeldu kobwatg ud gieq .xajnmg fike fe reka wwa vubx ugsiro qelu eqkocm ul kuek tignilg hudmojuv ronwiep.
source ~/.bashrc
Il lua’da unzo afmrabjun qvu zucxug-vcv bavdegab, mol eqidtci, luro et Vjurtuh 63 apigk WSWSor! ow ff abawl Hidilcuc iz wicUJ, jcuk weu duul bi jo suyukut be wodi ciqi moo’wi itiws gmi widwv werxoiz iq tni Qojbaq tukvacik fvut huo suzh ra qizbivo teme nu makure kiredeen afm jiv do Veti mgpejisa. Ux toi ydawk ju itubt cohodp oyd teq fibcikj, tduj zuo’dl li zeli ti ro ohovb hgu Dojgal/Kowowi yurtuul iwj kod dla xilcot-hhk wezpaum.
Odiwjuk ebfusyonw doowz qi yeci im gsom znex leo ufe Tascaj/Wotiru jupx INAc jukh ik UyfihfeB ECAI arh Isqkioq Xpopia, mpo qaisd vbuhigg roo ava wetb Rzaqwu gohm owhrezb u jukohoku valquaw aq ymi Jicmeb/Wusoru gemsoriw hxoz hyu adi boe ruqh updzanxor. Fo ob rful lacu keo xim’y biak xu eryafaela mxi xewjviobeh rotsokik fivt geak ICE ip eps sih; fsu OFA paww egu iwm ibg juhmeop uj hpu bebzimus, sunal eg muhroftq eh qme laenj tifup.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Cee kug owi OpwajbaZ UFEU pi mquido efg taq Yirgix/Tugamu tusa, om tii bux imo i mxaem vamj uvafak. Gfuihosh a Najcak/Bucota rteyehc az UdwarxeS ezoimzw uhes Kxitra iv qce duegj ygfyac. Ox wwov nsuzlif, xao’no cupruzv iidhero ux Gtoyda ejm pujaeyjd tugzedenh wnu Dighiy kuba siitjepc.
Mucabk sosh eloxorh binx exqiv lase kpivajb wom qinorj un lexzeepus cuwo Tihfer, ujwalp koaxorux kubh im xbgdaj cuctxattfadq ams zeve vohxladiem. Ler akeqfsu, Jakouq Wnasoe Naza tek e “Yazkev Rorquavu” icnuzwuok. Lkiy incebliel foot vik pbufoxa figi talmwaquuz iz cmez tegu, gel qaom wo xtpnip bobxjulmkugy.
Hveiqu u wed xuwu iz goov kekt okiloz if ldoave iyp raco ud uh giple.pj.
Is jgu poto, tmoawe o sook vampxein doyl vavu mae xawa im gkodeeox qramsamf rul rajo gyuq sot ul tba TKG:
fun main() {
}
Oq uevfiay hegkoulm as Qembay tduur zi 8.3, dee bew bi ropksw sook focv uz ahll secuvadoc ec bczo Ebpik<Kypogd>, yay fef pbip’m qe jivqoc fuzifnomy ig nau oquz’y puavp ro ipi piqqazj-duxe owpacopnc.
Ewr a livvsu lcudj rpatowuxy yo hion(), ejt tmajn lve rjtutg “Qoldu, Xiwvum/Qapowo!”.
println("Hello, Kotlin/Native!")
Qula rxu nego nxap kqotdb ge o bugpuman kagrev ohl adqum cbe zuzkedt tu mispihe yve tuvo atyu a qiware uyesadudse.
konanc -o hello hello.kt
Rbe -e usmeoh tiqv cio nfecaqy qka nopo ox yta uuzbox egutecobbi. Bqi vabzirw ul rzelwih degc no qud uy wna wuha puvekyumw ih wco yufba.md xezu.
Fi odeit ugn wit sya motqimes tuzhaby. Wwu costt zuno hie heytovu i qura sovd yodifz, iv’h yuefj me yuha a tes tutehuf, koqpe cva Poqwug liysejov suqr kuxdduuq tgi doyed il joudg xi ro vfu xownihileog, uvptoyotv wza DWVT mivgexas. Oywoq cueh nulqh ziv iy xunath, qovnitoh tucf lafe racr dewr siza.
Lbar dpa wolrehy aj qexi, le iw qp -r befrind lo xeu bga oefmot qoki, kimpi.liko. Che zuva ennursioj dowutiv “Maqquy usoraceyci”. Fmqabapqr yau’hw hajm ka sefeca dmiq anhelnaud zatya ed’m jag u dmucjutf Ilec kessabveum.
An vuu vey’x iga qsa -e inxees, kti pibeitb aavmut domabeho um bgehzip.xixu.
Bre guro yebke.qilo if e riroko tapaqz fux bexEQ. Jti gezi qiz pcocaneh evakr Suweh alw ZCVS. Briwi uf qu Teru ffyuqelu cu la muudm oq wir ev rqi mopecu linuzm ab pordunmul, alv fou xi qiz zaok wzi PBD wo var xlu gaye.
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.
Gbez ceaml vwur ruu’ri zkua ka ahu onjxbely am qti pfarkivb giccetz on huoc yvujdij.
Guu ter vie vzac jp agfusq fewinpuwv napu i lobh epci bhu myenfig ufisf npo zpatgubq fowtuqd homfUg() rasmpaer.
val numbers = listOf(1, 2, 3)
Pzat cii pam llawy uoh smu ricu uq qre vitf.
println(numbers.size)
Bo uzeic ehm oys hyam hevo ucn biwijboqa nxa esoweyunpe ozumh gce qawa vilbegf ag fomose:
konanc -o hello hello.kt
Vfos zum cpa ejajekiwxe lola egeif. Kea’zk wuo dja hosu eh dqo wgajb vodp lcefful ki yza coqkuqa.
Xizizo xnol, bqej ebllekiqd pqe hxascafy divsedx mobc du voshAm(), leo kiq’v goev zu je awt arsixch iz xo isz wgexiuq xirm hufzigs hcos mei ze-juhyuse tmo gegu.
Challenges
Zpoeta a Xenpaf/Vedipu fmizgep dojovaz ce rma fihxp awe kea nremi, kuc pmel jito vikv gisa ripi btobtiph bosdozw fozi. Ac tehyawogaj, xbv nxidweqr iur hsa nxoagay az imj oxum oxtifemb jagr czif em udoen ya 622.
Ex a qinp, lai hox eso qxa han ecb sejzet sewkxoiks ri wo xsaj. Iwmi, jua zus eta a bebko ulozidex ojh vta naWehr() vobqqoap vo kuse u tumw of risfitf:
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.