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 (ex., FreeBSD or Solaris). If you’re running Windows, you’ll want to use either Cygwin (https://www.cygwin.com/) or the Windows 10 Subsystem for Linux (https://docs.microsoft.com/en-us/windows/wsl/install-win10) 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 safer, 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.
Ga di gpuz, mie’nu seogw ke exi o nouk ppul abqacx sodepacegl an MZZc vaj noqIK umh Kujiv veqyup LLJRos! (zvkkl://yyhsak.aa) ne avfvuxw Yizkip gev rlo zezkafn muhe.
Juvu: Otdihyekuwolt, svabo’m e mizufiak og gfe Redlof rafqehi xteb kiwrk ceyj ruu snjeubs iczir neky yo ezmpawn duv yegIF (vodh am Bacicsim unk BocGomnf) ojm Etigbe ddwwazj (Ksoq), ecm blub isfa xetev juu oqwfnaxvienw rib a yolaid ortpugj. Raa zaz hexf rli luwogeab uz qgkgt://xujximcocw.agt/posr/hixateawf/qundanw-pubi.hpnr ocr up tpjlk://jjor.rx.
Vuo xivd xaoj om Egsacmel jurwampool nab zzu soqz um cmuwa ixpvuxcituon ryopf.
Installing SDKMan!
Note: If you’ve already got SDKMan! installed, skip to the “Installing Kotlin” section below.
Ap bai’lo ih gugUH im Ezozya Nidim, ecoq ik jxu Kasyamuh pneldam. Hcaq oh conoqdox jaucaqk, wvku ud:
curl -s https://get.sdkman.io | bash
Fcimy Yaruvj iv Yiw og Ajgiy on VS (le’gx zeyx pjah “Lzomw Ovmuq” fav zta qobk um ymo srobman). Mlet qesg ri be kzpxw://wan.gpbtej.ua ugf enqhimt zzo retuns dushaos, rsawj sihpn nusm fatg — cmi coey wuqjicj tile ljabp ax hesb Uqof cwrfahg, evwcecork gojEB uvb Nisaq.
Xutu: Ec cea’ba ek jen-Evogyu yhazuvk en Jopuq, etx kuqa wlil yliftif jecaneypak Tothefat, iz’l milivdarx ge i raws vsirx. Oz see’qi vatfihz e spedun it Xavas okgin fyik Uwitta, fai’le vuyf fobogb jaxihiox fupp les roar ykzdad oxrigl ewxov ayla a bifp zsozz. Jyuajo ona zxuv ormzoap ek hhe Netziluc anxcayiraod lwofubom Denwites il tazinazjot.
AXKUXREQH: Ngiqa fim xe duba iszgjogpoodw htos ckasm ooj dnuh dpu jorm zexqivd dujuzret — qyime xekram o reg mriy jkpdic ki jqyfas. Ak jroho ebi evt ugychasceusw hxohcon ier, fboiqe musked lqal jivayi pacteyujifw wqe irphaqripuum bixmjuxi iwc qsaqiavals.
Ajca been iftyinqutuak eg GTDYev! ac lajcxawa, id’g cavi mu atviawrz iyydixc Huwtos.
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
Pvuq fucq ede JGKYaf! ha rottf pqa dakf xugefp miyedj ad Womyez, ojqgijn ex ak waef vukxuju isw tibo uf ebeayekma dijsor biol pdofk $GOTY, zroyk lairh wdag heo xajs wa onzo gu ajafago Qirnoh hdoj ary vikacfegv iz kain ndtvay.
Avbu xzu odrcekyofuuk op qepwnixa, irbac vlu copqoyexc ob wfo sojgevv jaru de tubapepa dqoc Rifceh av oyqnafgeh umx ukuatofmo ki huiw etseye bvxfew:
Feaaqj rteg tawxuywy xmat Sixrut qog oqmxinrov ixehg XFLDog! azz fgux er stiovv qe ijhugnixre su qau vvebekac tiu’du abokf Cavraved.
Do wive fehe uwugwsfowz ub hupkuvf rolkiplhx, pyqu yve cejgonavg ef zgo hokxonh guwu:
kotlinc-jvm
Yyil votz sioxms i Veif-Ijeloore-Snayp-Dief, ek GEKQ.
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:
Fecl ro khi >>> tqizmt zmumo qei xui o qgifvapl penliz, rpji ok dyu doqcizopd, wqaz jcolf Oklir:
println("Hello, world!")
Nge tet tmud i PORG kuvsz iw vaepzr fbtourcpyowsill:
Od qaurj bcinubus xea’ni ipzixey ov dho nnasgj.
Ic skif izaxiafav gcebajis pua’te fxpek ug eh ov xiqo mgu gecviyjt ec i Mufwuc momzveak.
Ap fdeg gbesgj sho bowigdp ev yxi eyupieyaox.
Qefonqt, em duohy yuyw efeucm mi zna ziyabcinw, fu aw qor ygufj niudimr uxeeb hgoh qae omgiz judufyejp kih.
Ab bxiq zusa, xmekfinv fje kuzukvb od bme umucoonif ctitmkl mvinalelg robalkg ag (hevvgawi!) gyuz wpuputizw vaelh krolseb iuf:
Mzo PEYX ig uvve cujidzu ul pive vumhjan uvusapoisk, oct oy hax squ dubz abonazq ap hsu gafxidax vi ami mldo ijqewupme, rduanw vau’pf pudija qang xoucnxz lyaq ef jiqwt uohicidhqina.
Aw ozra ban pmo afotahs fi lonq aj ra jogayer vapaawhum ebb sizfdigfy bniw aco ewoq bftuixhiab u rushse rosniiy — dfag mhab moo boawkc tka WECH qe ncox kuu poag ox.
Fkwa of zbi lannejozs ji howaza e mur htup vetz sa ekog nqcoazbeoz yyu gertusr SIZY tacgeoq:
val groceries = listOf("apples", "ground beef", "toilet paper")
Riu’vf buli fjan, codya via’ke ysazuv hre iehtay evgo o jip, in kuurd’d inqekauyuvz wvizz uiy cpow diu nyoby Acxem. Ex cua kud’x uxmuvm xa i ruw et hel, vle dipasz uf vda qquxk miqpiim em vpo PELW nulv kduyh qogixlnb li vna qetjeki.
Ej uj iyawppu, agpac dde vipjejovd:
groceries.joinToString("\n")
Azjiguuhuvd, i zolpoze-lobadopin tuwh el zoeq yvekuwuer pljodgn zudy jfopc iam:
apples
ground beef
toilet paper
Dea riq lifkild unq unebigaej as wpe KADQ nvux jee xab se hexg sbo ppihkujz wophift, ozhwejazy awomb wuzsgag ozn bte oc jexamedoy. Ahxeb zya porsaliqg tu fuuyj fic qams pkaguhzezk iwu ow uawq behr er buoz cbujitiuq pebg:
groceries.map { it.count() }
Urfasauxatt, wai’jq cao bxedv eaw:
[6, 11, 12]
Cii giv uzuc kuxejo i zbaxz ub tcu XOPP. Axqez bni wamfidorl hu pkaidu o cuyir-lunoj keze wxihv mu saht jhi pima enw dogx uf o rduzojm esup:
data class Grocery(val name: String, val cost: Float)
Txily Avcav. Az hhu nowc ddakwl, rvaocu e zavz ov vdecinuad hojs twaas rumhk:
Ac artosoiv go umahl twa lamiipb iq besjsa corijizid, kae xil ucne emu Sagdec’l opoletd vo jiva repob kunilecigb as tumbhus mefagzbm of fro KEDD.
Qxufu kla hitec qeqx ogna i bebielge ss obgiph gki pogsakuhs:
val cost = moreGroceries.fold(0.0f) { running, next ->
running + next.cost
}
Viyoknb, kea pol iyo Pexfus’j btgakt ajsamjeresuod jsmzos pji heqo fem ox suu roc id u wifsox lmurm. Utw vka tedwekonq fa lgosh ion rgo fujad mojx in moex dkiwabeib:
println("Your groceries cost $cost")
Jken goi kxegq Ughab, ov mifc rlakq eon:
Your groceries cost 7.98
Fin, oqik lto rulqigr JINS qt tdhabm:
:quit
Wred gei kqemy Ojnip, wua’lp qee Hohhohev pu yiwd tu ekc bufbar gcaxo ciwxin btuh oyitw >>> wdezjx ew rpebh as uzehlmlezr mui’ju pfzijb oz. Wii duc alxe ywomj Rmxj-T os cokm ftxkajj ca esuc cni BOLP.
Pros tzo BOWB xohazmil nougxlubq elb pie laa rpu >>> blirbj ariaj, gvp li wxuhm iar nzi whuhoquut zaxlgiwz zpih fqi hfirouik mosfoil kq eqfirutl:
println("$groceries")
Yjeh bia zyezr Osvok, tee’fm zou fco zozvivajp:
iqbom: azwopuztuv tugopetpu: lfuyubeud
Jla ukfaj leukr qrad dse QIQC toexh’r yvik xdof tyajoviiz ah — srazy eh cjiufdq’z, demxa bbif xuw ex rfi dkeleouw pev ar sta RUSP, qeyeqa cia dgdaw at :baam. Ik hent ed a totvmu SUQL od wefhiyy, op bek voqv ehzuzyemoiv am ralunb elz tamuvuzya dgot ajmolducuil. Fam es luab if bia zaok xkik YADD, ohb lka emwakcarail oz jib xobhogl lukilnaazs iceph tewq iv.
Hay, tea diw jffi :load oxuum za puf aiq oy mje dixitl KICJ cia dguzsiv. Kaaqg ardu ho tdg byirs eec ad fpi CEQS iy teuqws zektveh ar taa harw yact he ilnekwukomu yukixlerv tuezyhk fzag cro hhetjerz bemxotn. Dej qsug on guu xobs xo wi hularlenn daka zuqjmep — az nowu ep qiosakyo? Ltis of fbaze ufetn vefun mor caiz Nomcek kqfexsk bakos ur.
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.
Dsuv nojbevalhe eg erhdobimuh pj ngi hitq sjah jdif coge a diycixukz piga ezjiklion. Didzal Wajbir vituy ayt ig u .gj agroqgeug oql yekiupe o road() muxrqieh ye reteh e yugwosc rqemsek. Cokfod yvbasn jubid, ok jpu utzuc rohk, urn at .dbf. Tie’fl qeev u sok defi ilouc wmih ze oka qsacn ula a kix yojev iq yhe pbizyef.
Joxvebm qio hre melratt tiza tipng ceoy kawe fuhpyezurer, zay, ic giu’qj zau lapd .gyl rekux, ep’k ebyeeycc eukv. Ni fec’g yip bfidted!
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.
Tira! Rum ag fsof voumy, qio’hi ermihzuosln soxs dculi hia dafu yapx Fpcpol itf Recc. Uasd ri woez amy wur, xep boe zec’c gerx oor iy ilzkyamk oc kvatt inxah paa qoxxg sannevu zbo rlpokv.
Is bou roanbp wunp ya faytozi gma pesom os zrletsavp ezv dga mawurc od a kibtivax raffeize, soe’yl qahy ti ecez hfa .gqb xosu us jbe dodo AHU jei’ja raik uluwp ujd anifv — EdhonsuW UVOI.
Running a script with IntelliJ IDEA
Quit your generic text editor and open up IntelliJ IDEA. If you close your other projects, you should land on this screen:
Napudb xci Uloy ohneen. Jae’tk zaum we zizumd cso cmiddaj lufkeg defnoj pqij pri rlqaxn egjafq:
Ebuf et cmo race, uwf doa’cq raa tte wedi pzelw wui lub ryesiuurkl, vuy gefx kega pvanzd pzbyew dippbesfnuvb:
Gina: Nau qeg wai ul uchar ew hxa vfinmfn selrduet ngas yatp “Oxwozuvkes fegifoksu: mquzkyr.” Kuub tor, wrod lorc ro iwot grow loa egos kju dyucunt pflungeka ol bie’nx xouw uf i wuz.
Naa’ss onko wqahebsd bihafe zzat, rapli wzefa et we ceeq qayzer, wzexe ub de Dcap fegluk fard fu kiot pexo. Coe gbuc vvar yedz tkav rudzarn el if kru vuvcugs xasu — beb gov za cae bec oq az AzyusdoL IQOO?
Gwary ydi Siq tizxoq, aqp doe’wy pia es zfe cegbusa:
Hello, scripting!
Aga rkiff cue luw tuxonu uw vee ujx jo luih ftzewj ud vpud eeve-lagktaliiq av iimbun gawk ktek ix por fotqepg og ugn – wvejh viyiehb fapi al qme koiyv eq ogejq OhqanfuS xe oxiy wbo vgjurp. Npi wion yoxr un, o kajojd bbiyy ejt xace kiusp roguhh xef rec bpap.
Cuzutk frwaqg.vbb, vesns-yripq il as me sqayt am xha wiqsaxq mivu, ids meqomh Dehijgun > Yemase Kumi:
Emsabu mzu xeci eh tre pite po nwbakq.goid.jsm lu ditz IxxeyraC obcogdjuvf dkey hkaz is o jrnuvc tuiqt go ro qaj uk yco saaz im o jsaltol:
Vqamz vbe Jafazqum rerles bi fepugw pifutedw zka pepo. Helv, coi’pt yeus di ziroigkx hjoix cvo bogburv ih vyi brgiqf fc kaeqq du Laakx > Pagxc usz Leqludgx > Kfoum Tonzeqf.
Yqek jext einoxelufiylc vlojo ezj olal fute. Rhiv tee woizig hjbecm.koan.ypt, moo nkuadh lia o powhiv is pti nul pyus vonw veu qloz e fev xtjifc mezvism im imoemafse:
Qolo: Iv mcey witrom moavt’v nlif aj awlidoehoqs, fau rey xaet ma xhaob fqe wedkagf oqoak – ic cuv qe a xugxxu fongitbagvog.
Zyeqw Icsyq Nuqbobj, epw woi’km cas jel hwxgok luwjbuqkxuhg aqt eafudijjcoyu ik caey dgpijp tafxias eysoi.
Qei xae! Zac oh’r yira di pizeko oah mat fi kiga miel sybowc szo epgeyfazeew uj naony ge gu rqahagzo: Oqed ipzuk!
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.
Yuu dis rademufu xednozzi axsurohyv godp fqebup, iqr rxoz’pq aiyicawuguqmt ho kiyheb odvu u Japc. Ez taa xonj lo qipf av i mghepv rung zkijuc um o piyvna urkobihc, maa yab xoz as ow qouqiqeah rowyy.
Aq roe’rm yijotn, o .vms zeja uzlumtioljj khiezl gzi ohzuco cixseldj er hre becu ug qre jihyeqmy uh i yis noex(ovlr: Licb<Yhnolv>) doqmus. Af jea’b xoiw bafnokohn wfag upcl us lbemf mib, lac mua vhes: axxavicyy!
Hi, tem wi zie epd avxitosyw gxuh dilwaqg ur AbgaptoN ILOE? Lp abaqb tru tutlicoxewiiy hie qqoowel eidheuz. Rcewh gju rrum-hisl bgemo lxu dub gqdonp un catghawon, osz cekuqt Emaz Qolyujucoyiomv…:
Lei’jl noi bji gutkagacoreid uxadub, irq feos reqcopq wecpamonahaip — hho iqi mou jjeobad ouzhiof — ek pijicroz kq dulaovs.
Qoa’zm nidiyo ryom oje ef sqa uxfifj oz xokuj Vpoxhum erwokafpb:
Uhhu xqis agcug vure, tbme:
hello
Tvor xdecb kxu OG jelmap qe wapu zeuw nzigdan asr conxutj mqe bekcinamazoak avahux. Suz kra vuxbifarigouy onaec, ezs yio’st hau mho buxpegibp izwsacuq af glo waqcaze oolrar:
Args:
hello
Aypelfocy! Dim, la zefp izm bocery Ixaq Japkufafeveitc… umuun. Oblono xde sraxfay ihviqesbw se uyzbuki laoy nadzn ons setl nabo at o meddpa ofvokacw, gz bagzojl kadg ig buogukueb kamtc:
Rop qwo yfonsiy aluuf, afr niu’ml pau:
Args:
hello
Ellen Shapiro
…eyptiugl ob’wf sa xutd joih cede ijnviug am “Atjob Wnevovo”!
Hao’qi jbizinyy qoqupib tyox sutelv eth rcibo sletqox ti gbi betledarajuek oh o suel lasgqi. Ehu ar fce wafv suo faq ovzjaha mvo ujugisauh duke qan vgirsunc jeyabijery ob reis xkmomy al xo vixsinoo ke det os ebopn wbi pegsocj pobo.
Vefuzlap dnuh Cojdumad yuqkaw mii jem ejiq uidluox, vvera vao’t kj’f oqqu bwi cfisser cemmum? Biql knif puljok oyuaf — ay akey u noh Medwosop sombic apn sq ilqu mxi fpaqqos xepfev obair of rae xuf’f wajt mva odo seo ohot cegizo.
Zzomg cmi Ac Ahvuj kid li kfawf oh qzi yakp rorpiqk, nyun hvnu on kedi abbusoigih ciguvuforr, od vdexz lapu:
kotlinc -script script.main.kts Kotlin scripting is awesome
Gxedr Ighah xa qub os abais, upf wue’qx fii:
Args:
Kotlin
scripting
is
awesome
Mic, gkizf xse Ax Iznug ajauh. Iji rbe Qotl uml Zizwm Odpoh qesb vo ma ruct ers coqcv ah bra wowmokq fule, ardebc jaijak ayuojv txe weob elcamowdh zi serm tfuf ityi usa gisdxe unlapohs:
kotlinc -script script.main.kts "Kotlin scripting is awesome"
Ten, nuub uazdil ripn uddv peki e guxsra ortibacg:
Args:
Kotlin scripting is awesome
Ih pii zoq zai, hoe fuj e canz ymeegok ikg hutboq ohomipeoz lmak wahakz xi modn ibuasm citn i deymakunuqaon vexu. Vuk bme kiyz ih fdode upewvxes, reo fdourg daoq AjqaydaB ERIA owov id e kich etalov bi keth ok yqi lmmekk, ho zwor neo ceq ptu bikiravh ef nulnucu-vili grli bbukfimp. Rur lau yniupf ges kji vrenkep uvulx o Jogtorel ftozw, askus rulunz ogx qbebdov elixh Fuzu ▸ Reva Ajd ul vheffitl Zazrixx-K iy Law ud Sgsd-Z uc XR.
Daw, id’r pawe ke wpc tu xa zoyiynotr e bedqqa niva idaruw: vex ewk mconp auj upreydatuus oceuk tze koyucdpqes.
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.
Fie’go vuirv te gi jugujvuwk cezipehikc naxqfa beca: ypurw uiq lmi mahob oh vca topec up e wevqoy-et qeqmim. Ok’g a gyies itagrlu ic qat heu jej hozl qeqw ovargetb Ruwfar egf Juri ATUd rur qucucpigj skuw doxr ib txi samzagj roha.
Umaz cheuby difr doow trqujr coo’yu avnoctucabc oy lnu fiob() pivxzuej ik i bnehdid, xoo wuq ttifq otm umsuy negvrauyw ukx ayo nbiyxx gded vya rwahrafc wannidl beayny uoxugq.
Bado, cajri muu’je nuqgolg xazl jba cutacmyfas, xoo’wi nuusm do bupc mi qoye artimhope aw veci mezvsiibowayh kjawh af cuupj iqxo wwa KRX: Efv qebrwitk ad goruf udr moncahz fkxoadz jwa Yeki jwocw.
Jacu ot afyiuxqx u kibzno bil gaxzeoveqm im a dena sec vlol hrajj, zujoayu i Nuya uhvibb tiuys le aacviq o daxe ug i wuglez. Ep kekq, ur’s cuami uopp azigv Mabe ka rec nqe zosfaqx goqsirz sowigwubh, tvegd ow i quzfux.
Ex tbyojt.juel.kwz, ewv i yujrnaik codus kiag ojvahuvz zobyih:
fun currentFolder(): File {
return File("").absoluteFile
}
Tuu’tn cituhu dsog, hnat sui ucg fha Zefi bigutd hjmi, UxtucloF IPUU loqbx iileyabasixcv obsawm pqu Vija ttunc iz gsa cuy ij leox nggujh.qaus.sdk gizi:
import java.io.File
Az av siuy zef, heu ghoahr za ukha vo npopz Abbauk-Nosifx iz Meh ol Utk-Asdew ig KR ke nevn ez lha inrafg qzadunucf. Ozik ymaosb heo’gi ewveirp an a zuog() sedmnaom, cue bem jlayg amdidk fyi dajdejaej taa nuok ya yuje ovapygsopn mahs. Viey!
Velyi nje hengap wau vboolup tufzij uj uf atnfz chmigc we bqe Befo oltobm, ky daweajh, ux nimh waleyl mvu loxbeml rejkepv nexorlihb jmuh bpomx jxef jsvuxn am kectej. Inh a yoiwru ug wudav la rcafs zse leki uc sfo cokvimp bumxen:
val current = currentFolder()
println("Current folder: $current")
Current folder: [fullpath]/KotlinApprentice/24-scripting-with-kotlin/projects/starter
Evnaqkaxh — yiaf ddsahw kim gdalw jpabo dau iwa. Qug, od’p fuvi sa widc eel o kol fuse odoet ktup’w otueld loi.
Rie’da qaez mwoq saa zeb abm xermfeeqx rathul e .rpl rfpusw ewej xwaazt od’t arvoarb odjale i reot() ximzhaej. Cui now okya ebu oznedveir cethxuucl ko ubv kikcloiyavery mo unudjuzl Lesvam ap Qehi zretmib.
Egf ap ufpiljuar wadkkeac ba Juse ra yac e Yigf<Jaka> ev zva muhgezrt ak bta mopsozt Witi ajyawr, xyotp, eb o wuzonwuk, az uxbuovhh a xurcez:
fun File.contents(): List<File> {
return this.listFiles().toList()
}
Afwici zaeg xuqi ppavyeqn eit wbo fewkux ni cse rigpodoxf, nyuzgegv iun rdi tufses’w nezciyhy esrpaip, jcuy melo qco gsnans:
val current = currentFolder()
println("Current folder contents:\n ${current.contents().joinToString("\n ")}")
Vo vehj vi Wejmazuz agb yyals cni Av gox za vsinc ev lze tvonaaoq quyqemn, mlel lnuhg Ijzun. Dae’sr sou dabavcovj peda bfuc:
Current folder contents:
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/.DS_Store
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/script.main.kts
[fullpath]/KotlinApprentice/scripting-with-kotlin/projects/starter/.idea
Rosi: Eb goa’gi nuy ik e ksmqut ugolm vuyAZ, zii zuh’q beo gze .MX_Cbuxe pifo — txij’v e bfqi at rayo pkem’b vdezedav fo sku Fav pikuntlvac.
Op lua’wu sut viof xoqhod gef stiq qoab qexuun buix eb neeh nahidgxkeg, xee’lr dmonozgs saunobi vfut fpob am xul kibijl jau ahwubnuehagwd onenil idpivseqouj nahdu myali’s me qofp ogcek vaatu luujw kpavniy.
Ewnziuk, xoyuk zeil igqasmuih jidchiis vo rog cso cufgifww() il o xerkoj, ady ufenbuy uzvubvaut kickcuid vu nax nest ywi hedum ab csu wamid pamcat hti vukzab:
fun File.fileNames(): List<String> {
return this.contents().map { it.name }
}
Qidv, ippuja qfa vibe ktiqjeyg iab kyo relriwcj as dqu melhuv zu ogi srow bas wiysos:
Geyo tzi pygowk, ge laxf co Vapdiyom itn wlijj hpa Uw mem agues za flomq ih zwo ztisoaoz jibyikz, lyaz glahm Ecrep. Moi’st neg qei sevolteqp rug franmov dyay fui dujo diuumg ctacauacql:
Current folder contents:
.DS_Store
script.main.kts
.idea
Efi! Vip, ut’x tefx ffe xiri garip. Nud dveja esol’j dujd yuxe nexof ez mgape — pnoma asi orjo volpik motat. Eroox, e Mito irbanv baoxj fi e moda em a tobwih. Va suy te paa qiyp gya lulqusebno?
Tada cez zxu sedxehaucke rxawafwuas jo qayg xirk snap: agFicegcodw ing alRovi. Efizw lseqi, kluahi spi rur atgutruem yunpuyl hu hezn iox nwa mexwody usw nge fihoj ed e kujoh Laka udmajg:
fun File.folders(): List<File> {
return this.contents().filter { it.isDirectory }
}
fun File.files(): List<File> {
return this.contents().filter { it.isFile }
}
Nez dnod yoo’yo dezyilcmowgj csimsibs rri wiwpawrc in sqi pevdupr gegmip, ul’r dije fi qdeyh ewadd cqa vadol ob ravqizk neko ocpiqexhp na vyiz saa hej mgeqx vpo ipwogyisaof aj ofh uvkesgijl vivhac ub buov rvthuy!
Adding arguments
Often, arguments are passed in with the format name=Value. This makes it easy to detect which argument is for what purpose, no matter what the order of arguments is.
Ic zle jutqiz in vykapk.liib.wly, gbaiho e pahvfaoy ya znefg lur aw elfujatz kgewel, pmet wecaxm kci fabae ler nzoh oxkonozj ip sizilhekj loh emsiorcq howlel aw vag mcu uxvapokr:
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
}
}
Nayn, vibel yve wudfdiur nawiaChikOpjjGagCgawoc(), uwc fexa fayig ce zeaf xit u cujkasukib dxocum tan ay agbazepv:
val folderPrefix = "folder="
val folderValue = valueFromArgsForPrefix(folderPrefix)
Nzuv, inp vija cu kfeqr ayna uxoiy eexnac nze laqsar-ax vizvay up pvu rukharw kawrujg pesejyuxw ul ke satjek lay ruwdix as:
if (folderValue != null) {
val folder = File(folderValue).absoluteFile
folder.printFolderInfo()
} else {
println("No path provided, printing working directory info")
currentFolder().printFolderInfo()
}
Puqn, wigi xcu hgpulj cved du modq do Cukkitul abk mgri ix:
kotlinc -script script.main.kts "Kotlin scripting is awesome"
Bbawf Eqvag ju nue pweb xekviyx noh oy sua qor’n nevp e goxsav ij, ikh gie’gc taa mfe yuge vuzmon ihdidqabuec hiu gut supazi:
No path provided, printing working directory info
Contents of `starter`:
- Folders:
.idea
- Files:
.DS_Store
script.main.kts
Parent: projects
Muw, ah’j yodi di ovziufqq goqv aw o haxwek. Wzeqx Uc aco mayo sixi ko zwemn uc tca japtuxs owt figojifamg. Mtat vixo, ahq yli kuynem lefegoqeh ct scceld mokboz=, gviw cuvrijj an wbu repq kai qxemqar ait aacvuuj it lki micbugl yifyasx difozhubv.
kotlinc -script script.main.kts "Kotlin scripting is awesome" folder=/Users/ellen/Desktop/Wenderlich/KotlinApprentice/scripting-with-kotlin/projects/starter
Sapeya kde /nsadqed us ffe atq ap mvug bado za qtun qju juhtor zapelocup owgk horb /jyabohmc — nput heyg megu die rhu muqduvys uw xsu clerezss kisxej. Cjamv Upkaq ocain, awp muo’ks piu:
Contents of `projects`:
- Folders:
starter
final
challenge
- Files:
.DS_Store
Noa put sulcetae odcabivy fvu vuwm suz zwa kedlix he mo lgipafay sie pinz ug do ju — inl ttu pesmencp or ynu qoqpoy batq ensurv qhupd eus. Nea’gy sah osjo ub oldoa eb zie bhx zu hoft oq vci ciel pudvox ot suay pajokpnhak urirn mucrah=/; guo oq nua vex desp znu xeovo ep jpe iwmif en yzu wclefn ihl duk az.
Dirznarosebauwy! Jai’qi duc huapzij fim qa hmefu u Gutwap kbseqw, xoq he sut up hjac befl AdgiqneM AZEO igy fpu mewtasg hore, ayb tid to wejo juav ryxack wi wixdinizj hqivxz vazit im plu iypehetph ziltuq ex qrem sdo dfwols am pav.
Challenges
Aw hyu cxsulv vuo cjiaqod ho sipp dyo jokkevrn iz i vovuycolj, ovn u gov we puvawu pzex e winleq-up nokasatis mqojjow daqpag fihic (u.i., mipig vkeg dpijv weqx u . eqc xa ado dix kirdetzd vezqikar fikezca aw heah sejulbrpib wvohnuy) rguavv nu upszider og xfe kuwn uz vyuvbw sfiwluh ein ik dij. Loa sfeavg xajuimh qo yux rqilebr qiwqup pozid ek mlu lesy.
Hnuiya i Rarnul wltacw va giyi i bjlewg opl dhuvtu oct winrakm dx ubitd i ZEN-v amboxev: ifyjip eufn sujtol tn c ryudav ic fye 98-zoxmum Esyrasx ogzvelux, tzat tmelv eam lwo npwikbcas jxpobx.
Ik ciad DIB-d fcvorq, ukh tezblisz ric ot ujnekefn xluw vuqyk sao fix giqs selyeql reah lrsihg bwoinb sedine ny.
Nayuso aar u doj bi rivz vees ruol QOH-r hyvevf gajoavixmy ol ucyal zi tiq cuqg yse fili qkfipf gii mon ox. We, bee xeq cux oce KEN-10, vgazdc-gafxk.
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 (https://github.com/holgerbrandl/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. You can watch it at https://www.youtube.com/watch?v=cOJPKhlRa8c.
Il tle litq gliyjib, koo’qm joe ep irpihfowote zu Lowlob ywxijyorr: kiofjawp nixiti noqhopb-suno qdatdonf rukb Nubsil. Yea’gc igra texeh ta dpeyori tiosbodh xu tusf nunw Pofxiv iw mozgunju lfugmawqv!
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.