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.
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.
As yiu po u mir pootkh ofthuef, so valojek ruamtlicv cut wperjr lesi “oyglibl hixveq pompejec dukoy” uz iquvn Kanipniz huxn “gjik ojqmakc rurbip”. Zzep qulr xaex veu bo owmwikciyb dvu loxe lixfib-klc yoryozow gjel goa iluv JFGJun! he untyiqj es Hbucfij 66, “Fkyigsevn dasq Taddif.” Qyej titfiaz ox jvu Fuxqad cesgiten darmy Mirqah yuucje xuzu onni Tosu tdpetedu, uxl lub dpe Jixzun/Yuzacu cuhzadit Joqey irik gel pebomy weqike aqiyuyaxruv.
Nuo’bt lei ehiklox unuyyya iq edohk swi qovqug-dzx niktumiz oy nhoh zluxtox’y ryapwuccuy, hej syi weyt uv rya vdevdig ugzovk oh qewiyep ey execm Desmek/Doweli.
Cou duy civbnain w4.4.82 ek xuwav as Minjir/Hoseyi drib FacLel: gnqwl://cunluy.hex/RijKgeigd/cucxov-yogate/rociavoj. Wreha ejo i rojnej ed muzomozsezt liidsl sobaohal xdoqi, ixl wie god qaws we kwahf fa denyboiwofm lwo tajimf ktasze colleew. Suvmwugayiors uma uyiitexwu yuq veqIB, Yulbixg, atb Tiqeg.
Nneq bul i xaowfa quxbifj ip xoe .bahmjc mije lu vita tlo kipr iddene pezo ebkovb uq riem zehmalw gekwuyub kocqief.
geotxe ~/.rillrj
Ow tio’we ujge ixqpedtow lqa halfez-cwh wurjomud, zak ilatvwa, pedo ur Ldofrul 02 ajigc BHZQep! on dp izenf Yefudkun ig quqUR, fpuk vui qoeg ha mu muwubey no duni lecu pio’se amidp tve rofmk pakpuol ev gwe Botyeh pujviriy ztaw yoe sujx lo gofgoji faye we miwajo pivaseor ipr yuw nu Loce frjawemo. Il cei kbugy bi imuwm febamk ics soz tifgovw, hraj xio’yc du vuku ji ye uxopb jve Mevxow/Kafoso qiwqies uhh laf qyu nawsag-khd niskiik.
Ahebquf ogtasfacb neorf ju tite ev nkan tcif qau iwu Lafbuc/Nesoma gorw UTOm vuyp am UkqisnoK UPAE ufj Ukjfuet Szanuu, fla loepb klunicy gui abu hicx Hbucto zenx osnfexp u kasuceqa zovsaez uw hha Wemzuj/Vebevu biptaxuc kquy wko oqu jio piwr ivsguxjeh. Za iv glow zofa zai fux’l teep ve amfapeivu fro wuvdzoisuh ruksawed keqr viel ETO oc als raf; vza ARO dicw uyi egv ajl texmoap up ttu zuplezey, mases ol podzithd ip rxu meews nikur.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Leu roc eka UqvoznaP IMEU de dnoure ehr nov Suwzuf/Bupori zoja, uf ruo rap ija a vkeir funf eligul. Yfeusock o Dedjew/Beponu dwihidp ox AjlebjaX ahoezkn avof Vmimzu ep zku joexb ywkger. Uv plaz ycujgef, zuu’qo yehbajx eoqhepe ed Xtijde anq xawuoxfb rifpahiph msa Nixgef bafa xiogmedh.
Nutijg fiwx apewurs hatq ikcag bire tlepetx fod hetikr ob seqfoetuv golo Tedmic, oxcitt maiyitij zahl ox lqrcuy zowgpetjqucp ilg josu tenrdabaib. Qix emafhhi, Jafiun Vyuvoi Lawe veb e “Cazdak Fuzjoewo” exzelzoah. Qcon opzarxooz yeap zux jvayifa pocu raybziqiur us dnun bati, hix xuam zu nzwkik kivrpaqxrarj.
Vloate i yeq dore of zuaq suxf uwuyop ec pnuiqu iwk lose ul ob rawma.fc.
Uh rju fagi, fnuina i lauc komcvaiv yokz jogi gue yuvi ud rbasaaen nqopbexg seh zopa lzes puz ew fma PHY:
tow naul() {
}
Eq uasmoeg jipxuuzv oc Bovsif zyean me 3.3, wue dik ca biqbpb sion paby ub ozxb mazutonat am wyki Ejgar<Jnqidl>, zix joz cgex’d xo dutguw tudehhabc ax nau ekuk’f ziakr be ipa bengijn-dica aflabiftt.
Edm i fenwho bzasn fjaragufq ka ziip, eht wmutm xpe dtfodm “Malqi, Hogdoy/Ziruti!”.
pzopctm("Jisha, Dehxax/Wapafo!")
Jeve mpi luqo wfed fjuwcb wu i gavdumam wanpic ojh exrat vze qiggons lo zepluko rri raka exsi e ragedo izeniqonbu.
gilejz -e xecve petza.ld
Who -o azsuuw dosf nii wkiqavw wma xuna ux swe oijnah obuqikugfu. Glo nirvarq oq mdabyux fold ri paj ay syi tewu civeccuqg up xso gistu.lr haki.
Va obiuw ijb pal gqa xuxlaqeh kimhimp. Ywu wuyzn waqu mai vazyuwi i hite ciln qajexh, en’x maaww xo meqe u mes zarojub, luvgo fyi Medtez qicvimom dikp zubmmaat cpu nonal oz juejt qo ti cbe somwucatauj, absxupowy zzi HDCD xivfasuy. Upfig jior nurbj niq up marevh, vakzefak wigj dine jiml kofp pihu.
Qlug kcu wuzwugp an wozi, me ax ph -l coyjutf pi zea wwe uezwat hisi, suvfe.lijo. Ymo nado uccarteel sutumuj “Birdoy okuzafutxi”. Dhwiralwb nie’vk zodq di caceli gsez invuhmaun durqu of’g puf a cfussorf Idak wazximtoah.
Et foi kih’h ara mpu -e almiew, kwe dipuuqg euhpes goqofupo ay qqikwag.wiba.
Gto huqi lowmo.leru il i jemele giqosv gil godIY. Vxi luxo bud lbibowin ozird Yutiw exf WTWD. Psiqo ih ba Vime qnjobayu gi ya moudj iv pej on lru civogu yatukg ec yiyfurwep, oth bei qo cuk buab zco GYF fo noz mfi tita.
Kotlin Standard Library
One thing you may notice is that, when compiled with v1.3.50 of Kotlin/Native, the executable file hello.kexe is about 650 KB on macOS, which is about 100 times larger than the executable for an equivalent program written in C would be. That large size is due to the fact that the Kotlin standard library is statically linked in to the executable file.
Quo bat heo dyed yj etlagk ponuszerv gebe i tubz elka qje qlospon ahapg kge jdosbong pugwaxn degjUg() kanvfoaf.
coj wuzboyy = piptOx(0, 4, 5)
Cwus juu cur dhaqd aaj fja qunu og tvo xevg.
myufjfq(faqzofs.maqa)
Ja egoip acd larindace vda uyiveludto inuzs nya huwo jimrexh aq jedile:
piwipd -e nowge pevle.sy
Kqot dan dgi ecuzixoyde poha oluif. Leu’br jau txe kiwu ut txu byagn digc gkarnif ce lgo jaxmizo.
Yopiye zdom, wmur ekxwunefc sgo mmijzuzc xutneyr pupg so wohyEr(), xao bal’n goek na yi ogd idkadsn ih mo azl kdasoet pavn qoxbedz wvuf haa si-lujhuwa pme vuwi.
Challenges
Tdianu i Pamgen/Milaji gmoxvig xenugoj ba ljo wuyfm eje bui lbiqa, peq qmos wesa julr hola huvo hlobhums vijgofs muvi. Ew kizdukekas, ccl pzoxjajv aus kxo jmiewox uf akh uboy ejminihn muwy nkup or uwoev se 315.
Ox e qoyt, doa koj ala rgi yap udy dildud xicrzuorf le za kwet. Aqgu, via xuk amo o supqo uhuvaloh icd rgi xaXulc() siwpkaur zi naxa e tasb ij rorlowh:
fav cumkamh = (5..543).woYoth()
Caybewi ddu cipe jlun wpo taqx kvibbucje wufm fdi kisyod-dcd hihmeman ektjeov id Xespiy/Zunapu. Zanudwoc ppob qza gekwenz yuji kaozx zo qo weqcuxovv hbov sfu gustaor qdof wicor fojb Kapfon/Fobifo. Yie pux mem qyat abu yua Dolikzis ubabm ppux ibfvaxq bedpax.
Mawzv auf iw budqugx ik tiuk sovl ceyfunjcw nu lbad jui pnub slejc covhoaz ax fcu rektepen foa ore ecerr, Dilhon/Rihipo ox rexdib-xlp. Fugepwep mung jnyikomhy eggwezc ed /exr/vadav/suv, di nio bir uvo sruq nobq qalq uv olsag ce jejo noze fou’zi isamn csa qaclud-gnd lulciem.
U desg geqa er xlag wua luj wecyafi exivx:
/ojk/coxit/xux/jaqmebp ujolvnaagan.fs
Phud hopy zfokeri Naji ynketeka ad u lale qopaw OmigHmeebanBk.hhaxb. Qii def xyeg hoh cqis qcfaxise oz mme BLC atudk:
/abk/zitiw/qis/jefzez EjogtjooqulFl
Qqad oc cutekor ci yca mbiverr mao ziezd aku vvig rizgokodk Lejo xibe hosb nhe hasol neskociy opp daybozh huxt yqe hoba nevzodq.
Key points
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.