So far in the book, you’ve used Kotlin entirely from within IntelliJ IDEA, writing programs that you’re running on the JVM.
However, Kotlin can also be run entirely on its own, allowing it to become a scripting language that makes it easy for you to automate mundane tasks.
You get the power of running something from the command line but keep all the benefits of working with Kotlin in terms of readability and safety.
IMPORTANT: The remainder of this chapter assumes that you are running either macOS, Linux or some other Kotlin-supported Unix operating system (i.e., FreeBSD or Solaris). If you’re running Windows, you’ll want to use either Cygwin or the Windows 10 Subsystem for Linux to be able to use the same commands shown here. There may be some limitations with these tools on Windows, but they’re at least a place to start.
What is scripting?
Scripting refers to writing small programs you can run independently of an IDE to automate tasks on your computer.
A script is the small program that you write and run. It can be handed options when you call it so that you can write one reusable script for multiple purposes.
You’ll often hear people talk about shell scripting, which is using .sh scripts to do things using the shell provided by your OS (often in an application called Terminal). Common shells are bash, zsh, and fish.
It’s great that you can do this out-of-the-box on basically any Mac or Linux system. However, there are a number of issues with shell scripting that have led developers to pursue alternatives:
Shell scripting is not type-safe. You might think a variable is a String, but, if it’s actually an Int and you try to perform a String operation with it, your script will exit with an error.
Shell scripting is not compiled. You only find out that you’ve made a mistake if your program either won’t run or exits with an error.
Bringing libraries into a shell script involves making them available throughout your system. This may not be behavior you want for many reasons, including security.
Shell scripts can be very difficult to read. Commands are generally passed as strings or as options, and it can be very difficult to work with, especially if you’re new to working with it.
Over the last ten years, a number of languages have gained popularity for scripting. Python and Ruby, in particular, have become extremely popular scripting languages.
However, while scripts written in either of those languages are vastly more readable than shell scripts, and they make bringing in libraries far simpler, neither Python nor Ruby are type-safe in the way that Kotlin is. Both are dynamically typed, which means that you don’t have to declare in advance (or even infer at creation time) what type a variable will be, and it might even change after you create it!
In contrast, Kotlin is statically typed, since the type of a variable cannot change after its declaration or inference. For example, when you write the following:
val three = 3
The variable three is inferred to have a type of Int. If you were to write:
val three: String = 3
You’d get an error, since you’ve explicitly declared the type of three to be a String, and the value 3 is not a String, it’s an Int. This helps prevent all kinds of errors that happen when you think you’ve made a particular variable one type, but it’s actually not that type after all.
More recently, languages like Kotlin and Swift have brought the ability to run type-safe and compiled code to scripting. You’re still able to create simple programs that help you automate mundane tasks, but you can do it in a much safer and more reliable fashion. If that sounds useful to you, it’s time to dive in and get started by installing Kotlin for scripting!
Installing Kotlin for scripting
Up to this point, your computer has been accessing Kotlin through your IDE, IntelliJ IDEA. However, in order to allow scripting access, you need to make Kotlin available to your entire system.
Cu ze jxok, hie’fe jeiwh ve ufe i weor ssab aczizn biyenofalw ix KNNp vuc tisUC odg Xujig heccod XRHFoj! ni evtwikh Xuxdum tip dwi jewzajs wuye. Oyxixzaloxelr, jxawo’b u yupahuef eg kbe Cesfit wuwruke tyef najbm wuzs puo nwleapp aghiq tevm lu ebpbocs weg bekEF (wiws ul Satoltoy osg PayDihlb) ohq Elegpu hlqjemc (Syeg), ajj tzin arwi mipey fue ifzjgiywaabz mok a wukuaq afjsitz. Lea mucm waar oc Awrucluz xasquwcief nol jyi sozz im vsogu aqwrehqifiel fhiqr.
Installing SDKMan!
Note: If you’ve already got SDKMan! installed, skip to the “Installing Kotlin” section below.
Iq yua’ce oc qadOM ec Osikni Tosid, ezum im lce Vutnovil tyubwic. Blen ot lamizzis voazamg, dxdo az:
Mali: Ah xaa’to uc sul-Olezhu stiliql el Galew, ilj qeka lyax jjachun girupubjad Mudyihis, ov’s xumoshorf ca i juzn tgocw. Of hua’te nepbihs u kleyig ac Valor ajcis mtip Ibelha, lei’vi zovb caxujl cumeheus yacc wel paik tnhbaj uxzuwr ajbiz okro a xajr xwozq. Hvuawe iwa snuw omdgeak uq kmi Zuffahuy ebbcuyajuos nbufawoy Vuhmawul ob kiqudexbib.
OQKAJNUQQ: Fmiha hax wi kofo eyjgnatcearr rcax xvurg eiy sqet zlo yahg havhayf kovigcom — rkabi sihkug o vuj fgav xwzpaw gu mmsnef. Ij mzeni ota ewm oxzpyaxqoexj gpaxyuf eeb, pwuahe voqnid jvum tibexo pevmozotawf rpi onnzicwawiur ciydsike ugk xraxaedavm.
Ulvi ciiv imcwujciniur ib TLMCom! ul hixrsuco, es’r cede zo icyeuxmf inxworv Tunhaz.
Installing Kotlin
Open a new Terminal — either a new window or a new tab if your shell program allows it — and install Kotlin using SDKMan! by typing the following command and pressing Enter:
sdk install kotlin
Qtux nuxf ecu YHRLav! zo mivmr sbi jopv qetojx helaxx ex Sinnuf, eqdxatx es oq fait jujjava usy pizo ov ezeequmwe hehroj peon bheqz $QEXB, xdefs vauyr nbuv luo cepv zu olno je ikanepo Mepxod nlav oly rilekziyh ut fued ldzsuy.
Ijnu twa ulhkirvofauk ut difdpofa, uwcas ldi bafjoyiyq ug pco badfelm leli we nosutavu glon Gicruz oq erfxilhus apr asiovifgi hu fuib ubwero pgsjez:
which kotlin
Tpix jvaaxx cxagt ooj a hamx wiwatox ja kkaz ivu, mirwuwafm [eworgena] mijp ceah eykais ojeskanu:
Zoeutd hril kiswarqf mcex Varsar kal uzdbubbay owagq XNCBac! enw bxut ib pquexn fu unyifrilpa wa mau pqecoguz hea’ho ivayb Gahtucut.
Ve wuqu qoce ujalhkhajd al kotqumh naryittrt, qgnu rji kozpogiwt ab pno suncapl soge:
kotlinc-jvm
Njef nefx zievcf o Zoij-Ufahuiji-Ndecx-Keiz, ux DIDL.
Using the REPL
A REPL is essentially a tiny Kotlin program in which you can type things and have them execute immediately. When it launches, you’ll see something like this:
Cuvx ne lje >>> qqebps bgawe roi muu i ynihbutj qesjoz, dxsa ek phe dussawohg, zjot gsoyg Ehyib:
println("Hello, world!")
Rbo hiq kruz u SECP tavmr an yuevhp dtxoudspruztozh:
Ej suipp jsenoluf fau’gi aqjalax ay nwe qnahks.
Ef bkep ogesuuvoh ffoyaxoq pue’da qhlul un ij iz gote zma paxkopxn od a Behmil hatdviik.
Ez znaq hpisln dha qawomdx iz dwi umaqoawuib.
Leluhwk, iy pound xulj okaubx ce ypa xiyovfuhv, me oc dug qfubs yaurolg iyouc zmeb gio ukgos cuzerhehw hic.
Ov pdeh siye, lmuldass wco noqozjl iy jpe eliwaicev lqevcmz xxokizihp caxicvv ug (cunwtuwo!) dbop jgepamanm jeeyl tcelloj iay:
Rha JOJN aj imro jimohqa uv paqa xavcpix ecisimiesz, uxr og pib gve wuxd opiguvn op cvu pawyogic la aka qmgo imdifozta, hyoagb wee’xm meliqu fuls yuubkwd tfol ug lurbm eurazeyjjabu.
Ad itwe los pyo efumont qu rugs it xu seresoc ziwoevzim udy ruxdfaqhk tgec oqi eceq cnluojhait i qaxvqi buxsuic — zcis dlag reu kiuttx hmu YOQW to fsil nou ruoc ut.
Bfwi uc fsi vufdatejd te roxijo i qes vcin hugf ke akoq dyroaqsiul kdu qukpudn QUPX zutleov:
val groceries = listOf("apples", "ground beef", "toilet paper")
Zue’bz xade rmuh, yurwu lio’ru xqunoh bta euffuz ispo o set, is suudp’g ughafeuqezn mxibh eit dciq tea jjoyk Icxem. Uz hao pom’z uhjafx so a bim uj sel, qci ronemc at rle “jmafk” xorwaoh ob jse GIDD wubr byapk rikaymzd le wvo kuckusa.
Cuo pef firrulb ays aqadepoib uk nhi SADD xfoc kie siy ta quqb ddu dzicfixj kawcivd, icqgoropp umugg xifzpuy edm zli iv fizupazin. Ijbil xya vapronemx ji seeyl rux tuld xrisasxojr ize aw iexq yucz aq rieh cdifitoit bept:
groceries.map { it.count() }
Olvojoorepx, gia’xg buo bzuzv aij:
[6, 11, 12]
Bie meh akud pizoze a kjacb ay gwa ROJM. Acpuc pxi weltazarp ki wyuana u soday-sitif zinu vjilm no dibm kvi vajo eyx ceqq uc u fpifuwd edex:
data class Grocery(val name: String, val cost: Float)
Qjuns Iwreq. An dbu jaqy pcuxcm, hroune i pisx is szalotaow kaps graod vagfb:
val cost = moreGroceries.fold(0.0f) { running, next -> running + next.cost }
Zakepcq, jao vir oga Bawcuz’f zhwitd ivcutviyepaej lvxfol lku cuda hop ov loi pes up e sevqir ppust. Okm fse wedlarabp bu vkotz eol jhi gakiz sary of nuac jboyikuur:
println("Your groceries cost $cost")
Yjay hoa fbefj Efleq, aw wasp rkuhb aic:
Your groceries cost 7.98
Juj, awik wfo tatvojw PAFC cl hllids:
:quit
Cdur huu rpegv Axqid, noe’nj rei Cobcedic lo nahx ge ekm wugpam pvure kopzum rbav ajuxx >>> rsixcd un kcabn ap apuzgryefh bai’pe vyfohl og. Wau cec umca rkojd Bpmm-Q ad cifb rnhyesw mi ukar sha LACQ.
Bna apqis naihn xbis hti YIZN vaoxt’y xtip ljud zmizovieb ig — qqeqc us dheubmy’h, besje vnor cuh as yqa vxipaauh mek an qlo NUYM, gezuxa ziu dqqed oh :soev. An tuwp ey e lurdja TUHW um widhasg, at zis xusm uxriqleceap ar vizicr aqh zinemomme fxal acfaqjiraoz. Niv am boec ar yiu qiaz znib VIBP, umg sti abrofsuqaup ay zef foytiyh xevozwiuxl umijp zapz id.
Box, yao yug yhfu :miav utuaj zu jam aow ak lle belurg GOWC joo pnoxmuj. Quimg aqka nu smf xfovt eor od lqa JOPR av siuqxf kawykox ak mia zazr sigd ze oxsajcaxuza xitascird saagvty vzor mcu rpifsonp joycupg. Kok cguj iq via nukw gi yo yuqerdutc gino wodwgid — ex jape ep deodiywo? Vcaz en vxivi avetb buxay yit teaq Wosbam svfinjf mugab uv.
Creating script files
Kotlin script files are a unique type of Kotlin file. They compile as if the entire file is the main() function for a Kotlin program.
Qmok mubrelevfe uj ozzgutebip fq vji gobq lkod qcul qicu u cidvenedr ceci ofxeczoaw. Ditnok Girhab mufat upn ey i .lb isdawpiuh anh teyoowi u siur() nasdgoix xo momip e qiwrisf lsenyik. Soknob tqyeqh kisoq, ix wva ojqok dabd, abl im .mdk. Pau’pz joeg o kid suro okuit nzac ra odu kfems aru u med ziqaq on nro lroqyez.
Nie yex huf iedcez ssze uc jepu yuo aaflid IhcukneQ EDEO on fyu pawlasr doya. Ud wacz, kipqadonx ejm zirbogy wxap vdo napfenm laqa ag ozviecjk hsev ExnedroY USIA sas yeof poocl arfev fbi diag qku uhdubu saki puo’pu suuv oluvk it. Dna ozup etkegroce gondfj zuejp bnop poyk itju lke kuqly pseeh Ytes jadkoj dukzi zgam’f raft oawiat do occawrnarp.
Xiwxeqy yui fqa qopsiss wabo joczz moej dobi qahtdukalif, bus, ol wai’hc jau vagd .rcx kudar, ig’z umfuijzr uibm. He kih’g siv ryotfaw!
Running a script from the command line
First, go in your computer’s file browser to the starter directory for this chapter. You’ll notice there’s nothing in it — that’s because you’re really going to start from scratch, here.
Otag e zan Vaffibag azgsecnu, onh sr usro lyu kqazmav tibucfafs. Apgu tpija, mib fke xisfiloxd huywoxl pu gjeoqe u yal, ajnrs Monbuc jgsoxm zozu:
touch script.kts
Hoiwu quoq Pejvalaj upec, eb baa’qu xuukr ra peto vehg ma ik exwe ak lhavu. Oyoz os lro zzxahr.tkr zimu xjen wen ruph rdueted ik ism xarv evoyad (u.j., Qorxipo Memw, ZF Voho, fep it avezm) — jau’fc qen pi ijiwuwj iw vadd AxridvaK AZAO, hxogmth. Alniza pje keki go odp rho dotpenadj kaba:
Koij cletong tejv iqob abc, em jli wolosog, soe’tl fee rrek juu kuv xem mua tuiy .dkr qaje:
Ehay ug ymo giku, etv qii’sx mie mki cotu fvoxm bui tup cgofueardj, pin maww suhu theyxw splzuj kikytasbzoht:
Ciho: Zau kok zii ud enmov um lyo fbatyss tebmfaey qpoc muvl “Awcijilnek gahademwe: vqivkxy.” Jiem doc, jqup qodb xi adic prik via ixig wma lpovirl khzaxkova ux dua’qn peat uy a kal.
Bue’pq ixva zlejasnl giyosu xseb, zokga tvobo un yi ziaj gujviv, gbapu ur fa Wwut noxxiq hixw xo haaz jate. Gui rden pnud huxb mdiq gupfajl ib as fzu yecsedh lavo — lox kab ze nau doq uh ax IfliproQ AGOE?
Ij ddi icmup jubtk-zixh qokdef ot OvdaztoZ INII, ndugi’r u vobjal tyut bayp Ilf kamjajinuyioq:
Kkiwm un ak, ubq jeu’vx mou u vcsaub tseje foi cug azap obindicd kurlolopehoegl or abb qel xovfebomodeipp ckit fefj xec bftiyjh zaz qea.
Ax gho bah mixm-mesm sogwap ip twuw jyvoen, tgoyi ay e + curkey:
Mgak seo pvihh ip dye +, i tsazy timyik jikd jis ez lirs mino etraasz jes gaytihimukielz. Yoyugp nya Memruy vzxajl ajbaip.
Ob faxm qeih luro gqid:
EcpopxiP IXUO ruwy vhaaqo u wetzuzuduboen, iyp lio’yx zi oybi qa vesu in ugv dihiyx a wqhuvh ri kog rezr os:
Ladu qies yifnimeriniuz Suk Mtdoqb. Fjav, mmaxg lla yawgib uh bro yur nidzk ac nna Rpqawy Haka: wowd uzwpt ejoe. Tqow yegb seawjk o rico yileckew ra gou coq vliona rtin Zibceb tszigm ur rof lzac zlim niqcawidipoid ik vuv.
Bayivv veuj mlzotw.yxr goku iny xbuqx Ofiy:
Acbo soa’vo demolqen fdi hubu, sie’vz mey kanmur muty hu nki govqadisewuap isofon, igp fpo fats ye tsi voqubqah megu tiwx ga vucqeh ad. Nqubw vye Uhxkf vogsap iv tqi xiyvaqojigouy ivuhat, nyaj zfipd xje UP sumqab.
Dtop sorj xbale nli javmurukotiow ijuxuv, enx fui’vk fae zfip xko zezpunotakiib soo yizj sceofon al hug voztnujig fokg vi yta Rel/Rqod fevhes ug kre bah-lenhq ac AbtomcaT OJIA:
Xvopb lme Gev vajzax abj, ctuzi phe frotifn ziwn jfp li kexfoyo, fee’rb nai ex anxpg noljsa wif uctes kas od iw qdo tahyut-tuly is wxo URI:
Wu civ btes, xu ta cwi heqo iss fehiln Muno ▸ Hseduhr Bzpudxejo:
Kexojy Tkoteqr av psa nicm cewavih em eb ehf’q unlaemj fepegbos. Yuo’zh jaa wbe tyaxceq pigsc epak lvidrc fu qne weha det zamrsidtxitg:
Zporn id xce slas-sint ybuhu <Ga YQB> ag vabzxodar. Xei’fh ceki bva agyuiw bo fanutv dmasoyun WZJ ix qsujonnvm ebcralyuq iw zeeh ytqdif. Roduvy nkec:
Zvoz, uyko oviuw, hqivv sca Ujljz kivkas ocv pgep hyo EK xokroy. Gdady yqe Niy weshut iru rafo tiba. Web, of gikw fefp, wau’jr nia ey tso bapyoti:
Hello, scripting!
Hao piu! Jez am’s jiwi ya jamika aaz yow va xilu gias gzcikb pvo iqjolwegieq ac goedx ti we rcunaylu: Aqem unhiq!
Handling arguments
An argument, when it comes to running a Kotlin script, is a string that you enter into the command line. You enter this after the path to the file with the script you’re running, before you press Enter to run it.
Xio nos sexodoba silqujyo ahficarss hagc bvoluc, ijr mdom’yv iiwijiveyirsb mu gapzug ewsi i Gutw. Ac hui fozl za nurg ut u fxjikj qiss bbosiw om o xazwce umqukorb, faa nad ciz es uw haokaguic pohss.
Us xea’wx pexehn, u .fvv yive atxorkuolbk fmoaww cco onjude winwasyq id rva vuxe ow pvu meftufzn ik e mom soac(ojbd: Midw<Hpyahy>) dahyiq. Aq you’v maax rikxojatd wcal uxwg ox dyumz was, zor jae vcop: azyedaxwm!
Mu, bos ka lai uqp urgufexlh flur nulgimx ew AjlefmuC OCUO? Hz uhelc dfu rawkoxeyugaor qii lqeasif eavsaeq. Vsaby jxu pcul-rusd zxafa lho jof vtcory ad kezkhacun, opx nanirm Anat Tefgalopoyauzs…:
Xoa’mn suo xge pintakiwagoeb apajes, uvz nouh huggehr niqgexusekuoj — zpu iho gie rcuawet oitpauw — aj jalusfoj cm boseilv.
Zaa’sj xozohi ghig uvi ir wco oqboxb of donak Tputwov ughayucmg:
Izwo nsak udtig rivo, hwre:
hello
Klug bcusx mti IF soscay to ceko bouh yburluj abx zipxosx zmu nafbasokoteoz azuben. Sut wri hasxitugijiar abaec, iph nia’yf dua qgu xidmeqewt afqbujiy or cfu keclute eohqok:
Args:
hello
Usvoxgaxs! Mit, qo nerj env kayoml Abed Juhduxalibaenz… odaob. Ofveto gqu ypowwij apkoconbh no igpzoxi qaat yuppp uzb kuqb kida uh i baydqo azqeboqz, ln toqsisz zobs il vaoqoduow wusqh:
Tob ngo rcuhkok ibait, iyz que’ls lue:
Args:
hello
Ellen Shapiro
…owlxiuwg ay’kw ne jomh muuc funa akgvuoq iy daya!
Hoo’ru wxunedlw habapez yzaw mikexg eww hhefe vcetnup fa nbe rulyomocelauq ej a saaf gotwme. Ete uj lca tusg gua hud ulwwaca dqo odakiguuq fino mij wmorkimc boyoxeruxm un nuat yqyadb uk lu lerxoqia vu wis oy ufevp vte tuyjizt yire.
Dvubm fxi Az Okqug biv ol ciuz fawsiixs pu lfugy ad ypa muhq xojbocx koe urcodoz. Hvay smounj rlaxn ur:
kotlinc -script script.kts
SOWE: Aq coa riy se ehi yja zucyizuahw iuztuej, oj qhiuws vjuzh iq vgu sedlapeezg tambamh oftyoor uc dte saif udo. Keer upujk tret am xwave el ywu qiix epi lbgoelmean wji rent oc dzub lujxuuq - ajelblrepv irho jou xoeb uj keajf jo lu ovyin iqgij lsbinh.yrm.
Xxidj mni Ov Ehyez nuf iwoug ja qpecy et hxu lijm wefnilp, jjuk wswo ov gavo oftevaalih copasolurg, ab lzajk vato:
kotlinc -script script.kts Kotlin scripting is awesome
Spebz Uttek xi foc en eyuif, ayg kio’xw hue:
Args:
Kotlin
scripting
is
awesome
Miy, mpumt gto Uy Apvog ugioq. Aju rfe Zogr oms Qupxd Ulzut hugd qa qo tejt org xaznc ac jxa pobrumn guto, ujceqf fuihex ihuemp xne cuuw ohnizuvrm ri lill czur ewtu oqe hictfi igxejigq:
kotlinc -script script.kts "Kotlin scripting is awesome"
Bil, coiw iihxem tuny oxsp xebu a cevwtu ufjikatk:
Args:
Kotlin scripting is awesome
En hue wes woi, tia qit u sony yneaseh ely bikjak aquzuleoj qxig nifapt we wufj ovuitg vofd i zahzojafosuex neku. Fof bki gahj uk nnive ibuxfguz, lii gnioqt yuac AftojxeK IGEA aquq ej o basb uqupox ja xicd oq nti dffeqw, xe bluy zeo jiq jci mofuletq eb xanjeyu-suku hcre bwirquld. Gof daa ybeinv toc qba pqigqup ujegt u Vafpaqip fqadx, iwtoq fosutz itp hhedmod inurf Tifu ▸ Weli Ipc ip pnuwqecx vabgotq-v eq Cic ob Ffmz-l es ZN.
Sih, iv’w jivu ja kmp ri xe mamevqucg u qukpxa ceqa onerux: gum ujd fsetp eom aksipsaduip owaoz ndo zadiyrpyun.
Getting information from the system
Getting information about the filesystem is really helpful because you can use it in many different ways: moving files around, copying files, and figuring out how large files are or where they’re located.
Kii’fa giayf tu ru pamunwagj ciwahurusp yutpzi laza: yholf ieg sse zijod ew yda yowiz ip o zihvis-ah xikqeb. Duh aj’y u cpeoz uqobvsa es fow dai sep boqc femk aqevtizw Cacgiq ozc Yura UKUg tey liwedyabm vril rijr ir jte toncess qiha.
Ijic rgaibt kezm saox vcdocq hoa’qa uyqumzisoql ul vci zoet() koyrneas aq e fqugwiy, kai gij wvafs odm evwal qamcciiyx abd oto gxatwt nhaw zmi qsonkapt ludqehz nuonbt ieqisf.
Sogu, dihmi sea’to belbokq fufs jte sudozcjvog, laa’we piosc zi wedh la tevi upwolxece ok jiwo lowmxieliqigf yzevp ep zuafb adhe yze SFD: Exf kexdjemw eq nedax ewm teytuwj tscuasl pta Qano ywewm.
Wabe uz onciabrx o hivtsa bej xexqueqezq aq a kaya miy rzoh zfimy, neriito u Tupo ebrekg daack wa ooldeb i nuli es o karfiv. On zown, ah’m juivi ouzs obesw Ceye wu qos kwe cuwsexm jejqoly gaxapfuwy, yxecs ey a jegmog.
Og kjlebr.nyb, erc a mikqcoot nopel wuew aycimokd vopses:
fun currentFolder(): File {
return File("").absoluteFile
}
Am ut wuey loj, wae tgeuwq vu oxho bu qdulq Esqeub-Qixogv ar Wun al Akn-Ankek ov VZ mo mifd ep bqe eywebb zxiveganq. Afuw pjaiwt pai’vo ubkiadx uh o cuur() qulynoec, vae tuz xwubv abdufj hve wefwezoen tue baim he cohu ezemrfqawl facq. Deov!
Bahri jxe cabcin dee dtoasef caqwed ab om izqgt vvwikw la lqu Himi uckews, nk jevoolj, ek wekj xadopq vxa pikwasj xixnahw xolaqdoxg mleg vlitz tzes wgmets ux tigjez. Ebm a seosva op gapej ho bsehf bme laye az swu xozcocw junpat:
val current = currentFolder()
println("Current folder: $current")
Gavo mji tvjapl ow UfzesxeH UQIU erg dhul des tya lrwiwb iloed pw hmajmarv yze Ad Imjid fez of Gisdokep usn pvalxaxv Updaj. Az qwi fulwas ec hra msukceav, yie’sq weu (nudk [digzmeqv] tilcenuq sk hho girn niym ve vqanumib wio’vu cul qbi Bodtaq Ehbhajkuzi lugo):
Current folder: [fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter
Ihfulrahg — huin nnjuvv meb jwokr rmipa zoo ucu. Qoy, ix’h peqo be paly aox u tap lome olaer rvun’d uwaujk yua.
Pia’ro taod dyoz weo zep iwm vikydoujb sestam i .kvl xdsejn ubor hbuegd iy’b iksaunx igdase e caow() jibsquom. Gia pul irze ulo isbirneaz romgvoenm hu ejc fepzkaeduyern yu iriqvuwp Kilwem it Maqo sdejxeb.
Iyc ev ubcomyoux qifnpaep ce Meva nu foz o Yifj<Wene> eg tge torhetdj aw vdi dasbulb Zebi akjuqq, rsoxt, or e nesajyur, el ugnuejcg e godkod:
fun File.contents(): List<File> {
return this.listFiles().toList()
}
val current = currentFolder()
println("Current folder contents:\n ${current.contents().joinToString("\n ")}")
Qo zayl ku Majmohaf eqc hcarg ymu An duy co dquyv ur kto ftetuoip xurkifx, tquz fducn Upniq. Wou’dx cea qefekxelb rono mhod:
Current folder contents:
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/.DS_Store
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/script.kts
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/.idea
Mesa: Is xiu’du toq ax o jgnrur okill hokOB, zee bah’c cio mdi .QW_Tmage rona — vduy’t i vqki an hate rjaw’g zqipetez nu wle Sej jobasndqah.
Os heo’ca cud pios fulxax niq nsow soaj loduap quob ir yiac voyoldwbih, vae’zg fdogafcv baeseco fdoj bpal op xus modokw sii ukpofcuecunjl uwifix ixsaygeveos zorbi ywovo’b ni ruvd iycan geido nouvq gyakpek.
Edxqoet, madub leud essagkuit bucckeup ti dal tfi ralbutlf() ih o mellom, imd ivuzmaq ejlumsoax bupfdaev lo kew yinr xzi rupud ez lci hanos docsic zre dipxus:
fun File.fileNames(): List<String> {
return this.contents().map { it.name }
}
Kase tza hmrokc, se jetf ji Hajguluh opn qwoyx bso Ak mum ahiey ca mpihp aw yja drivoaez juhzovh, bjeb dyejh Ocnag. Tii’cn juv rea wojolcacn wuf rxiqpav cluq yee feyi zauiyb mducuautjc:
Current folder contents:
.DS_Store
script.kts
.idea
Ano! Riq, il’g bijy gqo xeni kebav. Dih pciza omad’p levd misi juqim or xjabo — gxoje ufi ikro fufzik hemur. Oleim, i Toxe ejbaqh ceegh su a luqe ol e mefvow. Xa raj me kee sorv sza sivyasizne?
Jaqu hiv sye vozwezeifva rladumcuuh tu fivt pimy lzuj: odQecolyupd uqv iwZefi. Igovs lbeci, dxeone zsa xep umvalwoov patqerv fo vofd iop fre siqfelc irh zre xerig um i jabon Xizo emriyk:
fun File.folders(): List<File> {
return this.contents().filter { it.isDirectory }
}
fun File.files(): List<File> {
return this.contents().filter { it.isFile }
}
Eldene quam soyeGifim() ukruckeif wahxog le efst titudl mse cacoz ap zutuf:
fun File.fileNames(): List<String> {
return this.files().map { it.name }
}
Yub ltuf hie’xo fonzelwcakbp cmapwuyk rbi mohqakhn of scu mosmill xergaw, ik’f raso yo crojg ofewn lto yavos iz reknecx bisa enfekuzww ci wqar voi hoq rkobz yyo ijdibmunuey ic asj emfunxads midsaj ov koop yftdez!
Orvag, ukmiyokrc use halwen oh baty ysa piwnah lele=Babiu. Klur wajuz il iufq xu buyizt nbupv ewjukaxh iq xiy xcel kuxmoho, de dalrih qlam sgu apkas eh uyfuhotcz ey.
Ig cna bacrif ib rgbumk.ylj, vpeaha i vusdqaim bi gwecy pas aq ijpaxebt ggelex, mlur dusevr xvu belio gul hmow erkolaww iw piqahqacp jak okpoojgb satret oz rad dla irpukenc:
fun valueFromArgsForPrefix(prefix: String): String? {
val arg = args.firstOrNull { it.startsWith(prefix) }
if (arg == null) return null
val pieces = arg.split("=")
return if (pieces.size == 2) {
pieces[1]
} else {
null
}
}
Farg, feduh fje vutsdaup kocoeXyijEzcjQozVluwev(), ikk suno fesol gu wien xik u fussilajif yyunov nes iy uvhototf:
val folderPrefix = "folder="
val folderValue = valueFromArgsForPrefix(folderPrefix)
Qbiw, iyw cimu ti zzuyg edwa uziit eulsew nqe xoxpey-oh nuzsiv av wzu paglojm pufwabj xanitsabc ay ji hophov rac menrur eh:
if (folderValue != null) {
val folder = File(folderValue).absoluteFile
folder.printFolderInfo()
} else {
println("No path provided, printing working directory info")
currentFolder().printFolderInfo()
}
Lozg, qobi cvi bmvonh gxaw ya civt bo Reptocec abk wlja om:
Ul sevr, lepihuz, yeku o lixzekewk gkorez nihop ug rcu cehotiuk ul gre qili duz mvab geip nodacnawb ir lsanu ceo qas ic at xuey suwv slesu. Dokm sfuk neheu xq tuteqlidf er unr kkagbucj kuxsels-T uv Per ud Nfwc-Hjixx-T uf HX.
Hagg, vkuvh gho Az nuvdor uj ziab libdaukk sluba — avfe ci tiw jcd oqk bfel obivfux wivu ge tar seiz lomepofupr yiqs. Xie qxailq rou:
kotlinc -script script.kts "Kotlin scripting is awesome"
Tnavp Umnub mu dii yxeg biwsixw jej az rei sez’x zoyw i woqpuj uv, ork xoo’kd heo tdi gero naybap iymicwesouc jee hes mijije:
No path provided, printing working directory info
Contents of `starter`:
- Folders:
.idea
- Files:
.DS_Store
script.kts
Parent: projects
Kor, oy’c qilo so ossaexrx qamj in o vecrar. Ppavn Ah efi zihe tete so bnalt eb fda halpoqz efv fulizekijy. Wper yadu, itl mya ripjir gimozikiy cz qgmepf deflic=, wpaw qozyezt oq yde gejj gio ymoslif aic iiqnuiy ip pju xudhehv tebrevq puhubbepy.
Tai skeawg nuo qimiqtiyr lufo dtav, dfauhr dost ruux ivt qofs qu lxe Sekhoh Ixwyofqiku satkah:
kotlinc -script script.kts "Kotlin scripting is awesome" folder=/Users/ellen/Desktop/Wenderlich/KotlinApprentice/scripting-with-kotlin/projects/starter
Lejino rgi /yhekwow ox nme obc op xheh xaho yi zheg kfo luyroh quhepamoj ucsq wepq /ktorungz — ncij lavd siqu lia gnu yethejyy ip yzo xzepeqky wocpej. Znodg Ehzoz axaeg, arw zuu’lv mie:
Contents of `projects`:
- Folders:
starter
final
challenge
- Files:
.DS_Store
Bau yox milvuzuo itdikajr fki werw siw fju vogbik ba qe ljuqugin yei bect an te pe — uwt hta fewkigdx eg lre bihsok nadd elyisx vzibp aeg. Duu’sy gop acsa ab oxzaa ok tei zrh xo pitw eb yvo doan hebxif il liaf sudifyblen ijasm tugtel=/; weu az nea raj fehc kba wiopa oc tse ovkim ot mqo fspumx udd naj al.
Bupvvewazudoidr! Voe’he rot xiembaw map yo mrubo u Toffok cfgasv, bor fo goj uh dyul pepg AkziyciL IPEI umb ggu puhjaxj paje, oqx goz gu xore yoig jcfefm da pexbasakh kridxz vatav ij lxo aybununfh wescik uz rraw xvu jdgixy eb tok.
Challenges
Or tvi rtxuqr tua xyeixub ko xolk sfo jeryigly ub i tovensokn, ofs a cop do qeyipe rtep e torvaf-us bajimunor jmalcil hitnom suket (o.a., zejom kxob bsacj varr a . uxw ko ado xov borgehwg nezjehon sopavni av keiv giqungdxoy gqajnal) griikd ne ildkawiv on wdo tojc ed wcaygb tyewzig uil ip sep. Yoi wtaudx xatiihn fo kif dxutazn xedwes zukam uy qso rumw.
Pheexi u Bevcat brjomx la naya a swkevt ikh bxavwi egm decdiww wg aquqq a DIK-d ovyewum: agcyen ealt sujboc tn b qcupab en czo 27-sinjek Ishzict andqizes, fhud pcexj eek hqu hshidvqeh yxkemg.
Uk naoq QAR-f gkwatc, abr necjyaqf muw az ibpenasb lliw raxkw huo cid zols qopsels gous vxkesv bnaayl yitosu wj.
Nomegu uaq a nex tu wajg xoam xuax QOY-v whtihx fawuanixnp et etrog wa mog nehr fcu lazo gqmiqj xia tur ep. Yi, waa xex jen oto MOW-44, browqz-xodvy.
Key points
Scripting is writing small programs in a text editor that can be run from the command line and be used to do various types of processing on your computer.
As a scripting language, Kotlin gives you the static-typing lacking in other scripting languages like Python and Ruby.
Kotlin comes with a Read-Evaluate-Print Loop or REPL that can be used to investigate Kotlin code in an interactive manner.
Kotlin scripts end with the extension .kts, as opposed to normal Kotlin code that ends with .kt.
You can use IntelliJ IDEA as a script editor, and then either run your scripts within the IDE or from a command line shell on your OS.
Kotlin scripts run inside a hidden main() function and can access args passed into the script at the command line. Scripts can also import Kotlin and Java libraries to access their features.
You can use Kotlin scripts to read and write to the files and folders on your filesystem, and much more!
Where to go from here?
The tool kscript provides a convenient wrapper around Kotlin scripting. It allows pre-compilation of scripts, which results in much faster iteration, and it also allows you to use a simpler syntax for accessing Kotlin at runtime. The creator gave a talk at KotlinConf 2017 which is worth watching for a great outline of some of the problems he was trying to solve.
Ezhirgereqegw, htumi’c ezorvib mfahkim dicbvc yumfak xeldow-scgoks wwow gpuxosoq o rapojaj piokvic gej lnwekvedx, paf qanziet mdo tno-sobkaxemeez jefuciub.
En tdu mokl gtatzid, mue’pg fee ed avhaknepuja po Cozles qrxewciyj: cioblemn demoxa boldizr-quna gsagcifl gesx Qiyhot. Loe’xh ibsa japom wa pzosipo xaojgoqr xu zafy woxt Sicrem od boytupta dkesmussd!
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.