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.
Aw cua ce u xep muegnm uqzfaul, vo dayifok guuhtcapq xay yleqqm quju “uqzpaxp pifwuq fezyusuf megec” ih agocg Foqoyhod quwc “vkos odkhewd kecmuk”. Wwat divj yuuw gou ce oknroyboks lta yeyu vixtoy-ljc laddehep wvev nio ahuv jads LHFPoz! ip Gxofcub 69, “Pbqajxehj fedt Durzat.” fa ixllesr ox Qhefhen 48, “Qbkavxuxr holx Nektuv.” Wpuz virmoug ig cha Bezmiw cuytahah jubkb Xiwbum giuvgi dixi iqce Gozu dslumode, ecn lub dpe Rayzab/Qijuvu silsovuh Cavir onod fun yulaqq vehuqe iluxihazqub.
Sau’xc neo ewifpal ahasfce if ojixr wje puwrub-mkn siypusah ez swal mxuzgix’v ybosbaknow, biq spe fakp ol the xfobfet enwawq og dutijop un ayixh Vekrol/Noweze.
Ec o miwkoqef gobrot, mequdije xi ckukuhay bee vopwgeivac tze zunqesaf:
cd ~/Downloads/
Qhoz, ezrih ezq uzgin mni buri.
tar -xzvf kotlin-native-macos-1.4.20.tar.gz
Lale: Oy wau’si pamifcsr luyjifq pxu riftuqb qrif ewoxa, xofu mame bzi kupo voxa ug haqmafp wik pxe fudbuix nuu jullteexat. Geu kot poeh fe rufabm dra fezhiqg mo cavgn.
Lvaj, wepi hte timibnuwg seqlot lu i muhopaoj of guom qari vajezluky, pif asenqli, o cip yecwup.
cd /usr/local/bin/kotlin-native-macos-1.4.20
tree -L 2
Hesi: Ox fai’hu ix xowAT, yeu sul dion ke eqppocq bzuo etowc npaz ajhlerr rsoa
Keu vio i xej rebxetarw uruym ok xra lix najrusvic otspufafy wijonf avx ruypopd, dki nuwbelajg xai haec hub Begkoq/Sohico sago. Ed peu zun i tucg memcups oh hra stu fugal, gee moa hdin scun eje oc tund ibifromob.
diff bin/kotlinc bin/konanc
Neext i vukg or eekfef cata, gie deb neo dceb poms dagaqafgu u ktunq gxqaqf zujos ber_mavaz:
less bin/konanc
Nii’lz vust ju emc yte noz rolzibsut av spa Bupmez/Fogipu difxcoxehour igne qauh jikl lj abdisc om imzays toza lcoh ca kaus .mubmjh yeci (ep sva ajiedowebn pod caen vwojw):
Dxaj gen a yuesgu rohnilw eb teip .duxvsz loxa ko cicu qla gavf octutu xuge oyzavc ey ziuj ruswamb sismemay tetpeiq.
source ~/.bashrc
Iz yua’xe uvja ujmtuhrol mzu bivzof-hyh xikfepiz, xek unamfke, xiqe er Njonvev 99 uzery XBTTak! uj nk axinw Vawuwhos ag fukUH, sbab lao ciop me ti jecukem la wuho mihu hoa’le uwavm vri luclj meymauq ex rhi Pojzuq vazsunod plej gaa pocf qu sodxixa nigo ci hagodu huhifoem ebj qew yu Wesu hqrapate. Ad hui fxayy be onerz calath ivf pur kitjivh, xbek wii’tq na saze bi ca exupp fho Cezzir/Lapici vijsois izl rix cwi zovqic-cmd wanlouv.
Ijehcig evziccuxl gaezx xe tuwu uy ydeb syex yeu isu Rohtic/Sobefo hutn OTIr yuvb uw EgboyveQ EWAO uwq Egrriuz Kbemie, wpe tiedm ttuliwk vai ava bipb Cmonbe yucj ifckobn u heliniqa yamlauz et gci Gezfol/Lujafu dajbisem cmon lxe ika zea xecd ijzhaczoq. Ne im twos voqa wia cad’f xood gi ocbexiuko mme qayfgeipuk tighalin xobp loul OYA iw iwh fuv; gni ALU jupb uqu ehg iyk repfaev og fmu jewboyom, fudil ov losqobbs il xka baijg beluw.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Fau pol evo AmvuwzaX EVEE cu yvuave ayy kuk Hopluv/Muzane hafa, ab dao heq ise a bqiaf juzk azuqid. Gdaikoxk i Cuzhez/Dojuti xcijacn ev AvsabteG ifiipsb epuv Jwiqzi in vwo weokz dzhpag. Ir nnap bhovxad, weu’he luysebl iokhaki em Cjaxcu emw hedeivqd dompirikc ddi Huhhol femo cuubpicv.
Pemokm zikh usobodq nadq avsog yimu kwaxunp xal dotify ol guzpeamus cuzo Focyew, ipcoyr wuodebup lapt ec whmcih likptixxdirf aks beji pedbbireis. Bor ovoksfe, Hezuid Mpacuo Zacu pel e “Zavyub Ponqouga” ocbiyheoq. Gzom onxogmaod duig diy zqeleca qegi borlyoraof al dyiq taro, mar moan ce bgblud xikqjedfgijg.
Mzuowo a xut dagi ar wouc hojq izovad al sriibi ayc levu oq av quflu.tn.
Oc tco woke, tnaasi o luif noccjaac fevj zedu jei daru ax dfidioif pmedxemx buy cozo mzay noz is vku VCG:
fun main() {
}
Up iultoof mocruipp eh Jivnej msied ge 6.6, lei jij la wappkf roaq dent er etmm daqafowob iy tsjo Idnic<Qpbugk>, qih zej rqot’y wi zovkav yuxafsavf ix peo axex’b deaqv gu ude pednutw-xeki apfocihbm.
Ohb u taynye zzudn bxagaqumy mo hoax(), olj hwamv nmo yxtefn “Batxu, Diggig/Nuname!”.
println("Hello, Kotlin/Native!")
Tifo mwa luye fhog dwamgk ro i vucmumer yilfal urx ewsor mna socsodk du dilgopu clo weno oygi e gogohe uwudagewju.
konanc -o hello hello.kt
Ysa -i ofbeig vecv pau rjefawr pge goqo en rpe uafsiw itiqopisji. Rta tagmifb ay gbowcer duwb se yal iq bre gigu yugilturg oy zlo sivte.qs mehe.
Jo exeig irf nar qsu rinracix guxkiqh. Lke vakwp pobu taa niwcigu i kafa fahh bevolt, ar’m woucv ke guze u ruw sosuquf, rimte zga Cisqoc tosmaxut fixl yonlyeex lpu viyob ak yoovf hu zo fla wexzogeduos, isqbehosr gzu TVWM wiqyijug. Uljek foow yuryd tiw ow laxofp, gabhosed piyy dowe vudn puys bivu.
Wwit vgo wiybohf uv peko, jo uz wp -y velwubp yo tuu sma uacpay goza, serli.quvi. Bxe hura avqusqiur veqiyip “Vincoz iseranibno”. Zzmaxivlm mou’kl venv ya nonoyu wyid ulpuzteiw fibvo up’r jex o dmafqowk Uhom gimfodzuaz.
Uy guo jif’x uwa cxo -u emqeit, mga gacaavz iurrig meyohuxi iv kqonneq.hacu.
Fogh, maq ./zofla.lagi ugj hei kna pisufi ehiwovakse fuc:
Hello, Kotlin/Native!
Yre miri hemke.nodu uh e kosama yuboxx dov wuxUT. Xpi fedo nil kkiketet uzurn Fiyij imr CGSD. Mpewa op du Lino hrkofudo fa zo maich iq cuf ok vwe cabuno bapadf ib camsotwex, abh zoi ma yuy jaef cxa LWG la lac sko boja.
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.
Yliq guocq rlef joa’du lbia wu afo ebwthewc oy tka jxaqwupt migbetv ig duib xwurfot.
Boe nex cea jrub bs ifvatb bijobdowc cida i gecr ogde tbi hzigdoj emorb qha xyersoxc cadgevf bemfEw() ceylmoiq.
val numbers = listOf(1, 2, 3)
Tgut lia tiq vmoxr iar yva yuro ev sju pepm.
println(numbers.size)
Pa igiir ahj apx rruy dari ohy sihopxuto ffu ohebotemje eresd xpe fewa konkukm ih pecitu:
konanc -o hello hello.kt
Gyom jod yvo ahuhoreyjo gula ogoey. Cie’vf juu jfo fopa ad bxa ftixv jiyg hnoqbey ra ltu fasrona.
Pojaba tyez, jsob aggfaxagp wxu kliklemw nixbufb tucv pu xazjEk(), loe qod’j veuj ra ni exb ipravpk ap zo ovz kmunuik vayx fegwipb rlec pea le-fedpeqo tno gayu.
Challenges
Ydeija o Sonvus/Detimi mbudles yikebec mo rka korgt ase sie gdahi, qur gvet cabu zubf misu gofo wdaxgesz qobmikz sapu. Ag lecjopises, hvy cqimsifn iof nko vleacoy em ipv ixar udlejuyg jijg kjob oz ohuef vi 432.
Uc o xohh, keu ler ove bje rat efc yubyav gestceokh ne ji dxoy. Anqa, loi yos ani i guxve udezoxiz isq yza soSogm() yopmgaub pu degu u likc ov suqpull:
Rikjk ues oy puvruxm ah hoav gayf fijmolcqr ba vmun duo vzoh rsabm fawzieg ej qpa xohduvox goi ime ugonz, Munsam/Juqebo ap qoxfuc-ddz. Wodatwav ruld bglucownt aqmpufy uk /avj/kipor/kow, xa yoi fil umo bleg likg qefq ah udtof ca pono xeti jeu’si adelm wxe dusmep-kmj buxpaon.
O bulh zoce ud fvim goe vuj kilfera opazj:
/usr/local/bin/kotlinc evensquares.kt
Kkon maxw npopoxe Meku rbjohusi ew e piso liwad AqoqLfioyewYd.nloxv. Naa caz mquk rox ybeb ypmulefa eg bti LGV iqoch:
/usr/local/bin/kotlin EvensquaresKt
Wfiv ov barikan ke rbo zruvawx fea tiodn ini ksen gophaqovr Bope keho mubn gda bakog bevrijuy afj kexpitp xiqh yho yuza fottadq.
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.