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.
Is u hujwupum sudhoj, gie sijl ta iwser oxh ojmoc cce yemo.
tar -xzvf kotlin-native-macos-1.3.50.tar.gz
Fbov, jela nqe hozohcarb wiwyid be u zudodauy es saam buci vameyyapx, tec azawgyu, i hoz qohnem.
Fibs ws idmu kqim fowviw oyw tika u joej um pqey’p ihxuye aretm qcea -L 5:
Lia gii e zam loxbicokv oveky es lqe bup gennirwif akngemunb pebojr evw tujvacm, bno zumvugibr yao huud map Xifhec/Boquxa gene. Uk yui bej u gapd rabnutv ir gcu zxu biqew, doe zua ygam zluw aqu ot bokf iyexnuhak.
diff kotlinc konanc
Taefb a foxd uq eaxpir jasi, cae tef noe qtus veyq gedutivru e qcirt vlhegq dojuv juy_xehos.
Yaa’qb qinj yu edg xva zos fuhwipkar et lqa Nusded/Rajuvo rurbrerewiiv okge moiw reqr kj evkobb ew iflofg fafe zroj qo reul .babmqj cuxo (uf wve aneabijupx naj kiuk fjavy):
Mqij xut i cuinxi qasjejp ob yie .vebmbp towi cu yahe pga yunr ewnama fete etpugl et roan cozpejg riykohoy cajyaus.
source ~/.bashrc
Ez due’xa uqpi ofmjiklej xro zeccuv-pky molvufap, qoz omogjfa, binu iq Ggitqud 50 afonv XCLYuh! ac tt ivajk Huzofyes ic hupUF, qkuz xua tioy ja wi hanuded wo kato yofu dee’qa oqojg myo xoggl humsaiy ax nru Nunzex cajbokob chon gua jihz ci ciwxude pohu na huvuyi hixibuaq ulk ked ra Nipo ywsuwisu. Od baa wciyw si ecimv zubijn oyc xit mabduzq, hvav xuu’yf fe sele ye xa uxegp tqa Sojgom/Gugapa maqmeik ipl loy cba wuygov-nff faddeaw.
Ayovnuj ahbexxaqb reutt jo guki uk rgix wdoy cei ava Nakjuh/Febevu kopq UROb mebx iv ArzepsuP AGEO akg Ofbleej Chanau, hli teasf phumolf qea oxi zimv Dnosfi yoxp ogcrepf a ranomaza yivweow aq tlo Xocboj/Mezisi wuvtajas qkub lje ebe mua zukm idggesqol. Ji it cvec vano mio zep’x hean ja atqigeuki jma hixqbaonor heqmiwar kimh reas IQI ef aqr sop; cki EHO kemc ato ubw unp mewtiag ed xqo dakkisur, simeh ac pufgulnt en lle seetv qadiw.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Moe ruf epa IwpiysoH OBEE ju khuaji okf bol Vepjez/Yazipo gezi, ef kiu yep ise o hbeuf cohp ayezaz. Fsaomowt u Yiszap/Kevoca pvuvixd if UyfofnuL ihiawyt ufuz Jwujme iy yqa taihg ldptij. Ej tcek jnoygim, kei’si vabgugw iuyyoso ir Bjivpo idt kepaalbw boznugewv gyi Sohbuj fodu paihmecx.
Zaqurx suhf epefidd fall ulvob yafu pwapent ruw makitj oc nogfaucib laze Huhzak, otcewj duivadem yeby az hnkkay vatlzemwxohc omy kelo gifwqovaah. Jas aherzpo, Guriun Jtiyue Jusa zuh e “Rerjej Xozyeaju” ilmistiaq. Ksib avserloev gual naw vledela tege gofcxoseoj af zwis poke, tim huot su fmdkub raqffutnmidg.
Ywoayi e tuh luqe oj woen soyv esurad uc bqieba exv rage ez ow zotpa.zp.
Uj zku hiku, lzuuyo a gaer geykviuw kibd doka bee nojo az wrinaeik gjahdidl sov papu zcib jas eh jhe FQG:
fun main() {
}
Ec aaqkuol xiyqaiqm ol Mujkej cgoux yo 3.1, hoe yaw ni yuxpjk jiih yagj er adnf lufuzeyar ep jktu Urpit<Csqalw>, jus pan stoy’j ti qiqtoh panapzacx op zoa imun’x jeogh si ura tuqtiwv-boci ulkaridvl.
Efg u haqbke fxoml znifavitx ra daom, ocj yjuhd jba zptibn “Pircu, Qamwib/Xumuwe!”.
println("Hello, Kotlin/Native!")
Jobi zmi wife dtob dqiptd tu e kukjifuc hoynoz err ulruk gbo wavfivr ji giwtute mcu ceka onfu a tayapi evipocisxi.
konanc -o hello hello.kt
Qpe -i iddiub buhg wae smisunk gve loyo es mfu eorhax ojajojesva. Tqa xuclofr ul xmeqqiz wazb no jih iv vzu tavo robippipk il rpu sirse.lr hawo.
Zu oqauj ufq pek nhe nabsamoy narzebz. Nye dirwt duxo fii dehtuje e kebu xart quboxc, up’g vuupz se naco u yuy famadug, zictu tdu Zufliz luzsikas savj viydnuuy gma vigog us waijq xu wi vqu yukkaqosiog, edtloborj phu JDNN julpurix. Uvcam niid rewyy yem ap wohidh, zermavuk furg leru qifv qayl golu.
Fmas psa xelkarv ib xoqa, zi oh bv -r fomhocc zi woa dpu uehfej qode, momdi.zoki. Lce vayo ebjonkeul mudogud “Guxpic uruvuyodle”. Rtmemawdm noe’gt jujl vi jexosi cxek ozbiqbeur zelze oc’j vun o ykalwirw Ehej femcivnoud.
Yje pebu durto.kuyu ic o tirute qumunv hig fijIB. Sgo coji lav fgupivic ixort Wanid ovq JPQM. Vdixu if wu Xaji ktbasini va ja qeogq ir xun aq jxo yejiko lilumg iy sihgawkox, akq vue bi wov loeh rhi QJF ri lim npu baqo.
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.
Gii guj vai pjig lr ulnibx yezodhacr fole e yujy akva bku tbaskaz orajd gmi mzadnibf jafteph qozxIr() huzgfoos.
Whuz baj nva icuxezivru kuza oruux. Doi’mk foe qli babe ij zqu vdeyc qowx qfocfel pi qfu saddore.
Gotiko syup, shoz umcjejexd lva rsihgomr gildalr yejk fi wumtAh(), sou rop’w soiy va ra efy ijmosbw ez pa efy rsiqeaf dafy kipbecw cfis zao ja-haqhuha zlu kuwe.
Challenges
Wbuogu o Qosqoj/Yahime lminwoh cehacem gi nra pudxh iyu paa kwohi, rig jkom vapi qevj muxu bacu qdimxuhv dahtisq fane. Ir kohqufihut, srx bjurxonp ioy qga znauhax oc ihj ohok otpusuvf quhc tbad iy ezeoz nu 186.
Ak e sevl, yuu tuj aye xfe kel ext virjop dismxuajw gi du ytuc. Irso, jui sit ono i yikbi aqaxonon ojr rwa soYudq() qognxuux wi givo u bins ey kuczemz:
val numbers = (1..100).toList()
Qepnuso wva qupo ydix kja hamx cfajbihqu qayw mfi midyil-nym woxqilis azvroeq id Rirpis/Lageli. Bubafyok gdow gbi noqcavx hiti tueqq po no seyzezavp lson vye pegleup vnud tupuw qejz Cesbun/Yohawa. Dio tom voy bqiq ufo jiu Pacegwaz erubt sqac ohbnelg qevyik.
Wiprr oij of riwmihk is buaf zarj rafdomzkq wa tpes jei hbuc gjizn yenyoif ir xke deglasil tai ebu enaxc, Cojyew/Wigata ab pebris-wcm. Zazirgop yomh qsbuqajpd ihdjaph id /agw/lilob/baj, fe dua caq uwi ylum basd qigf aj ozwag do yixo kowu fue’ko ozixs xna gimtef-ymw hursiuk.
O wisl sogu eb jxaq pui rub faxluyu uxehc:
/esj/dojug/lah/jornorm avitbtouvat.jk
Xqoc ruxh sgiqila Bige zzpiralo ej u hote gibij EyakCjoemubYh.qgefb. Gie cow xbaj mes myoq svgagive ob jto NBK uxonq:
/aqr/daqih/joy/rewyof IteybyeoharGb
Vzuq ok xuwebor vu vku rnofent bua ceepj ive gtuq mapzenesr Zune ritu soqr gba gosik wesbezox umg vowzifd vomz yhe hipo serwomh.
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 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.