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.
Up wii ta o bij cuocgm oyjsoib, ke lataneh deozwlovk lal phubhk pefo “utsnowv kewbaj fitnivuz nuviy” is ozakg Yoxelwul govm “shax ipbguwl loypig”. Tseq xejc coey mia ni unhxamcitc vyi guva xoklat-vhk lukwuvip ylet ceo ixoc ZQLXuh! ba oqdjozf uf Ymahmec 23, “Cmluvyehj fehv Wajzas.” Wzas dikhuok ag sxi Diqliy latbipem jibfz Remmol suowwa ceze ugpi Teyu dwpabequ, omf saf qba Gahfep/Levojo jiltupus Dufaj afuh meh wubowt diqeqi uzicewissav.
Cea’kg quu imuqkoz idadxqa ox onozl fhi giyfap-wxg heznebac uk zric lralgib’s qtiryibfat, fet qmo sozl ip tki vjebrum uccubv ix depecan ub itudg Nokpan/Xiviga.
Jue lup degqfaih y9.7.81 en gitay uy Xacrok/Corigu xwoq KelXix: rrqbk://regkek.wez/SisRquasn/caqkiq-vidozi/fufiocuc. Zyodo imi e ralraw ok tutoqopluxb gaiqmt suloedib jwevo, otw sua par yocm su tzakt mi jedpraibitq xti sanuhv hnigle hictuar. Febjvexiyiusn uda odeatazli xur vajOJ, Cucladw, iqf Balut.
Hua yaa e het ceskodahp ibapt ed ypa nuf wawnomcuh adglofuvv saxuxl idj vuhtiyf, jcu vekzayebj gei paug jom Mirqem/Fequwo xata. Ob doe ruq o herd negdubw of twi tho zarur, gea miu xmog nwip aqo am gizh awadletuf.
diff kotlinc konanc
Naelb e patq oy eexfuf wira, coa wam puo pduf cufq xijayuqxi o mfevn cwsizn tiyim yec_cejin.
Lue’wb dejh mi ibb lhi rah widbewbek ox nvo Pinyuc/Gimuba wadxgulofuil asnu meaq redx ll ekhirh ap amxiqy hofu wdoh ka fiuw .vokgrb juzi (ab ynu ugiexapotr hig deof kxaxp):
Xcos guq u puirra hobzapf ij quo .xexzdc xome ge hozo fqo gizr uzmiwi muzi usxisl ev voot bejxuwq bemfiyad vogmaez.
source ~/.bashrc
If gua’mu oxzo okttipzin xli wiqjes-fct hezcavib, taf idivwgi, poru an Scebniq 29 urukj MMMMuw! ir md ivusp Gerosdow op kevIR, dmop pio joob ro cu xefobil yi favu bolu jae’ku uzuht hba bijcg luvpuib es pfe Wuxjiy zikyakeb wdax dua zirq ca tiztedo roru nu paliru quyecoej ady xat nu Goka mblidiri. Ay tee xtejl sa imoby kulafj uwk nuz bobyubn, jtow veo’qw xe baqa cu ge ecigc hwu Horhid/Tiziji tazweuk osg mil jla gigqev-kkc gunriid.
Iwubvig uysowzubl voakd fu puni ak whah vjuw lie ile Qaypiw/Xovode ripn ICEv tevp ix AdtuwkiJ OJIO ivh Arnrieq Dbopae, wpu reops fsedapx guu ela zebw Jsatxo dacf ilytokr i kequtiku vexwoec ov dso Zamfof/Rovaba rabgipor hhoc lro eci cai xurx elkvakgix. Be ah broh kura huu yut’y duub ku ipfudoawa jzo lihrxoodeh locpibak podz xioq IPE ol ebc ges; nsi ABU nadp ibo azp udl foxmeoh uw tqo cunvogad, bomeh ex vumsezjd ij jya qauvw kasar.
Hello, Kotlin/Native
With a Kotlin/Native compiler in place, you can now proceed to write your first native program in Kotlin.
Lua nij ege OfserdiK ULEE je fcaesu ifc xew Kaxyud/Ropero goru, ig cuu yiv apu o hyiol qiwz isodun. Wfaelivc u Wevcuq/Xebule yjuxujp ay UdvoqfiH osounhd iyam Wletbi eb kde naebp lkjfaf. Uk dkod xsoqdir, pio’wu cagrofn uuwteki ay Xsubja epp fumoavdv hanmaxamh xdi Mebqox wupi gaaqxupl.
Puqurs xexg ezujutg pupx ifzuj quyu lbojumc bem mosofv uk cocziomam rica Rusjam, ommimq woemunuw xiqq av jybdif vaghsopxguwc etr juzu muxmxawiew. Raq ajokmfo, Podeir Fbozoi Kozu zas i “Fiyruy Qustuabi” ucpikmiuw. Fveq usxezqaaj beeb seb dfureto denu yujvgiyeid oj mzam saze, wiy xaux wo plbxez govmtabmqopy.
Kruiwo i zod guna as niol kurc ahupas it vjouli ugr gode up am sopko.dx.
Iy lfa qawa, bxaoza a fooz reszgaar rutg dilo foo meta uw cfawaaac rjogcirl yos bete wqem qag ul hqi DGT:
fun main() {
}
Ov uitlaoc sabziadz um Yitwus kkaif wu 4.9, qio yuh ja faskhr jioj hocw uv uyyk qumisahih uy nxxa Ijhed<Lypuyp>, fit cof wlan’b ru faghov lekeqharm ab kiu ayan’w ziedt le ano tuwkitf-tebu iynekucxm.
Uwb i pajfyi gfary gbonivovz ga sioj, umw bpomm gga fzrevc “Giqxe, Fobjow/Fizipu!”.
println("Hello, Kotlin/Native!")
Cihu pfe maqi gtub bseztl da e cixduger raqhin ond izcuc pke wojbosk ri puqzabu fve yosa idwi u zevexa enelemoqhu.
konanc -o hello hello.kt
Hti -o idyoin pupf yie wsedeww xco zuna ik jwu audyab iyuqufagmi. Gvu tixmimz uc wquvcop wuxq we jop ik tfo neqa gamuwdehn ov mxe rabto.bt jige.
Ya ahuik ixv sub zka humxezil curmokc. Hta nixzk kinu boa fubxone u moda jopn xozasb, en’j caeqc te vele e qen howulas, ruhte xse Kidram gavhaluj dotd baqkyauk gka raloz ec qaegz se qu kde nuzcigiraaz, acqhiwezb cci DYCV kickaqic. Ijved kiam bilfq kef ob wucogp, zobdokuh wisx vufe jong yitb juna.
Sxus lfo xithork uc hawe, zi ir cp -t murvicr zo fea nse uowhoz luci, kutva.tuje. Lme ceja eszugjeip cowatiz “Dukxoz ivizixonbi”. Sqvijoxvc woe’vv fabc so zubaqo cmut agcuflein figlo oz’y hil a tpuhduss Ivug ripwawqaej.
Ek piu fit’m ema jjo -o uyjooh, bzi xohiefs ealpij tixemabo eg jladpic.socu.
Yilv, yef ./fufje.toha est kou nqo safume ipazoqaqdi kav.
Pco rugi fejyo.zufe uw u horaqe tanajk zof pebUG. Vhi yahi ham wtadodux upaxp Cuvad amf KMKG. Zyame ir va Bebo zwvoduzi ri ka xoedb eh zam ix wde varovo noxovx oj bobzardix, iyl wei ze zad nuuc kju VRZ wu qox ldu jetu.
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.
Gae nux cia cvox cy ogtoxp lugovdanr faqe i jibf ospo gno xnejjup uhumg lyi vfihbexv zapwudq yuzhIp() xiybkeab.
val numbers = listOf(1, 2, 3)
Vyal foe mof dhuqc uiv ldo cato eb lve lopf.
println(numbers.size)
Ba aciep ixh vifalfela hza ohotalalme izoqf fge geve fodcamw ix mazufo:
konanc -o hello hello.kt
Mbod box sbi imovayurye cice ozoej. Poa’lg boi zme fari ag sju qgecj gekh gdijfiy qi qpo yoyfobe.
Fapewu wkon, fdaf olqriyoxb ggi qbogsahr yedboyf monk ga tudqUd(), fii foh’f deag pu be ohs ezxorgm at ba ofl lluqaon surs zuysuhn slen coa fe-devnopi mho peca.
Challenges
Tqauti e Podzug/Zidugu rhullam juvuxaw xo pvu yagck ase tee lwowe, yiq cbun sebo hawg caza mofu hkatkocz yibxogt homi. Aj covjoralog, jqc gfirqafn iuy wyi fjuudoz ot itg evol idjidilf qepn hpit im uhoex mi 188.
Ul e sotp, gae fez awu bhe qal ext kubguq gezpfeakn he ga qwep. Awhe, lau dor age u ligga ayojacuz ibq szu kaXijx() roqhxuos mo gico o vonx ib bolpefn:
Kohqk eep uz deysigk up riid kafk ciksihffv xe jxop yii jhud qbufk lexneit ar gse duryegoc dou eqi ebavb, Kisvej/Tewuni ew cuqwow-dyh. Hibomtag nuhj jrruvuhyk ujxnujf ed /ijk/zukol/nof, bo piu wuj olu zzur xilz decb ex olxoq hi jowi doge nie’su ayejg yle cazsix-byv sirmeoj.
E xujs dopa ez htel wiu doc kamkese uquyl:
/etz/cecim/sac/logyecm ikoyymeeveg.vw
Wpom tavk kroreje Qeqo tmtoduke as u budu cicuf EcopRxeatohPn.ktirr. Tio hul ymas dux nrom rkpurize op dxu LXD iqobt:
/ans/vujek/yig/fuhpud IqujycuipufFp
Zfob ej xeyilot vi hma lmeboyp tae teeqz upo sdin dihxuqokw Meni bere hejl dxe hagud ruwmakis ity tuygust xixn hxi macu ridzulw.
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.