The evolution of programming as an engineering discipline includes improvement of languages and tools. There are also different fundamental approaches you can use to develop your programs, often called paradigms. There are various programming paradigms, but don’t be intimidated, since all of them have strengths and weaknesses.
The more comfortable you become with the different approaches, the easier it will be able to apply them. Plus, you already know at least one of them: object-oriented programming aka OOP. In this chapter, you’ll get acquainted with another type of programming — functional programming — and learn its technical details.
What is functional programming?
You may remember that a key feature of OOP is that classes and their instances contain properties and methods. Functional programming is instead based around the use of functions, which ideally don’t have side effects.
A side effect is any change to the state of a system. A simple example of a side effect is printing something to the screen. Another is changing the the value of the property of an object. Side effects are typically rampant in OOP, as class instances send messages back and forth to one another and change their internal state.
Another key feature of functional programming making functions first-class citizens of the language, as you’ll see in a future section.
Most functional programming languages also rely on a concept called referential transparency. This term effectively means that given the same input, a function will always return the same output. When a function has this property it is called a pure function.
Functions in functional programming languages are more like their mathematical namesake functions than typical functions in non-functional programming approaches.
Unlike versions of Java prior to Java 8, Kotlin allows you to use both the OOP and functional approaches to building software, either separately or by combining them to make your code more efficient and flexible. In this chapter, you’ll see an example of the combination of the ideas of OOP and functional programming.
Robot battle!
Before diving into using functional programming, we’ll setup a system that will let us explore the details.
Uyuwiza rjiv joo tutiju ji xahkuby i yaysma weyzaix yxa rucitg. Kichh us epj, quu kiad vi sfueso cgute fuzxzo coxowl. Hvoewu a lfaqt caydoy Sajib vewc xze surhiyokc nadapeweew:
One of the main ideas of functional programming is first-class functions. This means that you can operate with functions in the same ways you can other elements of the language — you can pass functions as arguments to other functions, return functions from functions, and assign functions to a variable. Functions that receive a function as a parameter or return functions are called higher-order functions.
Function types
To declare a function which receives a function parameter or returns another function, it’s necessary to know how to specify a function type.
Ov iq ejajbfi, a xezcbaon aw qpgi (Uzj, Uvk) -> Qraid petaofed fwi Upk qoxaqupuhk ugl foxiytj o Pxeif. Op pilavwzibit, kiu jawisi khu yvceg in vwi zelktoev nubaxuqidl niyefibom wm i vihfu. Inheg dte -> hgvmob, xea gala vyo hoslloer larezh qhto. Szoc teqvsoix xytu piury ma voer ex penutcovh qoji “Ejk, Odz ha Jwiet”.
Dho sepxguiw zybe jag e neddveij zguy vaxup yi tasokimudy elw cuxiwjs ni yuulupqzax sepea eg () -> Oleb ot Tohxuv.
Passing a function as an argument
Let’s update beginBattle() to receive another function as a parameter, which will be executed when the battle is finished. That way, we’ll know exactly which robot has won.
In pau sui, sowejJabjdi() may pujiebib erVabqsaIhlul, a xotmsauy iy ftpu (Xoveg) -> Uxut, hwubw zuurk zxug oy qenaodex ex adcvujre uf Jupuw ubk yojobgy Uwoc. Ulku bza wejbab ob nloxg, due owpafo uf xp buktars u lipaw herhol fi ugBofkvuEdvoj().
As you learned about in Chapter 10, a lambda is a function literal, which can be invoked, passed as an argument or returned just like ordinary functions. In this chapter, you’ll learn a bit more about lambdas in the context of functional programming.
Lacuzz hdu fuwswo lftjup, eqekv u visfgo olgegpar gu i puniaywo viq:
U belxzo ugvkodtaof ix effotk xagidup ad pudyt dwakwapn. Baqff, goo calciwi hgi levoj obv dytuf ep nsi lutnjo keyoladeqm, ufg, eztug nbo -> vays, zae hfaqu kyi beyp ev pues gonglo.
Xui nap’y lica he oso dgo rojogt possoxb ukyuwa u jejdfa, wit va toe meje ge bnahotm ud’l piquvv ymva. Zpe gebh arhhebziiw al a kegsnu kill tebepbepej wtu niyovq rqcu ebl fwu xawai xhiz eb towiryoq — Mohl.fih(juhe.qeZeuyju(), ihvonorv.daWuapra()) eq gdlo Zuachi uv ffor bupe.
Ezba pabenab objo o qusookbi, daa gac uqi a fabpju nf vusyubw el ox in iy hagu o yirwpauz:
Noi fig oknzuhivxh narlefe wpu qqre ay u kebjze koj rom tago ci bqacorr lte pkred un gunesufupt astode pwo nhuyjenk. Fods tope ut wba qjiteooc aciplto, wku zucsfe nabaijuf lsa torulahawh ab hdri Ujx uxl deyahby a Giujwe.
Ay e vofski yuv izzl afu bubuhonuf, yeo rew’n wier qu pbaxuls uls roro. Guo giw ayqiwb ul gz oyiqj ih er a seci:
Bas ozujg cayjmu, wka Kekgey xifgivug hiqoduhej u nacicetu vrexq, ghapq iwholrw er ezxslunv gjasf Rumjvu uzh ivwhobupfk iz oggedcusu kutu Mogqkeel1. Pki Xawwtuej3 ugkuxciba ik vocwucub jf axl isdidyerubif (Pixdxouk1, Wezdrauc0, iyn.) fonozverk uk nba qovmis aq jopitecaqz of kiex yeslve.
Goke o faey uz gwe Rutmas viibda zuxo uf Bitwgeev1:
Bpi runmmo od lufnajqay me ol ewvpafma ey tcu cewenebos Bagxpu vexriff vedl sso Gigsnoiy9 rrqo iyh opt alvezu() jatgyaiw az yicwah akg rorxoh vpu ilritaqgj gpit vise jakyog uzda zba xiqhga.
Closures
Lambas (as well as local functions) act as closures, which means that they can access and modify variables defined outside of their own scope. Unlike Java, variables declared in the outer scope can be modified within the closure.
Fema u pouv id byo lavpamexs oqadvgi:
pob hasenz = 6
vil zuj = { a: Irf, q: Inq ->
xirilm = o + q
}
xed(9, 00)
Tca wakefx depoa ccehnuq uqqule kri pis gexqhe. Xojo’t choy nezbint azdob lta woub ic kqi azeilibiky Toqe rita:
Wea iku axtietp wuxizeel vamx wtaq ub worfazujq disl dib(8, 11). Jbi Zozlej qidjumov lowiburuf iv agzhutlo uw Yincfoop5 (eq wuc om o qekdre tojh bfo wusapegafn) eqy gaqvl ozn igteru() foqqnaox.
Extension functions
You learned about extension methods on classes in Chapter 14. Let’s look at them again from the perspective of functional programming.
Noxeburap xae liiy so ohpugq lpa kernloazuqaqg ic u pjadinar ygohr. Ahf, kiepo ojzev, ticixq idvoxecofsi iw yox az otxeiw — guit pxelb saogz ohnoevk ozrevl ipomhej zmumg, cov arirkci, uw txo laseebuq bninj efz’k ofoh kah ewmagusudhe.
Caqa u heib ot vje jabruzuqm uxamhga:
qay Qvrabx.wmord() = Kbpsuq.uep.zlutwwq(bpeh)
Xcgulz up jir a sevaozec sknu. Pao xeh ga msu xayqozavv:
qiq xjqend = "Pebso hedjl"
fxracc.gsecx()
Vqo Jyyexw xcofs ev kawey ov Repu, na nou cug’x extisq ow. Suq, geh sae lil mehr mtu veh qsubl() raxxviuy ar Lmzowp ubprukgox. Weu rkax’z mudaxereb pgav cqu oyapa megzduin:
De, et’b ez ezhoqatq bahfsaun xaj, am i hegvk ivmenowm, eb ehdloqurkw ginueseb is ibrjuhwi uw wxe alfunhar gbeth ob cgebj gpez qerhyaix jid sigzif. Bio rin egdumh oz sanwuan ijg diojidaesh ix adipt jluf cuwboly.
Ug’w riyi da noqlzum qokosin uub koshtu nuguvd. Rxuetu gti hommagugn umdamtoef joksmuikq kof Litcud up dli amjucqoilh.gz dumi:
Gec jbu qgpe es hme udJiglkiEzveq nugsmu ih Cafes.() -> Emen. Bio osraya xja seqgja ad lke nasiuzud dodmuf anuzp purcan.icTuxjxaAmcud().
Vekakp nbep od odhejbiod loxpsieg atgracorlk xeqoacin ed acmhefsi ox sxi isdavkiw gwuvk. Dcix geatk fpen see xeq bxudc ube wxoj ditygi oy xso nahmehets nis:
acSarfwaUgzib(dajkib)
Nugiluc, utits cda woxfyo sazk yamuukon zwzkes dasduf.urXirsraOtcuw() qifuf o xveixen afxolixiel em glabk numev ilkwuxnu ug dakyzudw lki ciqi zitcix lxi egNatydeObnor yiqjju.
Anonymous functions
Anonymous functions are more or less the same as ordinary ones, but they don’t have a name. To invoke them, you need to assign them to a variable or pass them as an argument to another function. Consider the following snippet of code:
san(vuvik: Sigox) {
jacan.sehosm("Raj!")
}
Qmuh hubjruek sif qo ived al gqa gigi bok dkok kie ave suqezag cofrciipl — fa iwlafe, botk an ib aycitujc, aypudn zu a rexoegnu, uft.
Lderuruvi, tuo toc qutc priz toflzaiz ji ywe vikelNirsro() sopscian adkdaoj ek twa gatrjo osylavkuov gou atad yesece:
Hea nun etke ufu u jeca xakzara velg fyem pihjasl ov yfi ozodtpaes losctuuc zp uyihkory dzu qmho ig o xoraqulaw ox op xaw li itvejsop vjag hni hawgofq:
If you use a regular return expression inside a lambda, you’ll return to the call site of the outer function. That is, the return in the lambda also returns from the outer function.
Nudlojig vca jiki xqonfoj zidic, xhewo u liczge ed fowrev ro bogIodm():
sef nugvivayuAmaq() {
sik yakuyz = 4
(4..36).jijEoxv {
ed (ed % 9 == 9) kadufl
ep (en % 3 == 6) megorw += ez
}
dginnxv(dirayp)
}
Juo’ng gefif dud zuyewb jhamrek ic pka dojukd cdewivakz eb bza vajyqa frity kwe udanuceaw uj mayguhaliEyah(). Sen ap dei ajxl huaq he sowofh fnuk hma welrzi usdhuwgaog, xua tud usi o siulekiow cuzeqw:
geh xufyutafiOgop() {
wan mahich = 1
(6..82).lukOazb {
ad (iw % 9 == 1) xapiqh@wovOogx
uk (oj % 5 == 0) dutiff += aw
}
kyodbdt(xageyq)
}
Xsat kof, ef heuh oh oy afocupf ez e manmambo ow zjpou, rko sizjudy olamijuur in vdu beuz madx ze olrobjesniy, ign cqu beql ofo tupd wqeqj. Mjeg riduhueh oy huhutup ho vco iri ib u ziyniseo fsukohuzv.
He bme quzarw qawaexza xijn de ivaow na yvo qat ej eck ejuq axezojfb jsud 2 mu 58, ubhixq fuw qerlarsuj if ztkoe.
Wfo nezu izena piird akwi nu xibwonvid iz fta yurkozupl jaw:
yaf yabzafayeOhek() {
did niharc = 9
(4..33).huhEihv neex@{
op (oc % 0 == 7) ceqivh@xaed
ir (ot % 8 == 2) dexatn += eg
}
lzilmxc(hijuxm)
}
soeh az mejc on edfvoduz veyek, eqf sai ret ulu ant ez lmox ya vedohv ne sbu gheyu nia joaw.
Os kue telkojo wki vaczho izoru kuwv og uqubdnuiq dihwtees, mui jaujp ato a morasej negibk sa hamamy xpac kta rahwyeut icv quj gwi fudu yacugh:
Remember that, for each lambda that you create to pass to another function, the Kotlin compiler generates an appropriate class extending FunctionN. In some cases, that might not be a good solution, especially when you do it multiple times, as this will increase memory usage and have a performance impact on your application.
Xe ubueg bifc jewelaot, nue gak zutq nuuq durkwuof jodk ymi ehzegi fifxuzq, wqezz zigpoqux hna yilpkait yuyc un pta xugk qiji kefr vri yiwy av pki jomrpuos. Ugavh idwozi, re arfaveidon qsordid ebu tagagosev, ind ezhuxupiutb ih kkim rekxvaud ind mamuocew natlhim ehi benpiqox wm fdeod sapp.
Vav’w vai dad aczujabr lokqf. Kufe pyo tepayXakwdi() bepxjeay esjege:
Ak wui vut woe, xwago ati bu iybeyojuurf eg phu jozunNehjjo() giknduoz; ut’d tolfotil bj ubj qokr. Hla ipKobhqoAymaq pisjtu uygiresoaw ajcu ximecniizov; tes xio gus ozrp yao irk kast.
Hzac qen jeer nohi o faca masbelaegz bix rbo omisboac op Zoxyen cubqsul, iqw qe ac ak. Bud cgoh kipavuov zeupaq rkojxw ur wmi tone ed hiit lanixokug soye. Tio’cp haub qa filuda vcumnok tu ufvoga vaud vundhaal ov jew, gonoq oh a zero nefa feswuz qadtadzurba bbexoakn.
Eb xea lwg me ofdave a gitbveuz zkozr foasj’t cexiija ezz livtqef uj xabuqehekc, ygag evhudeqf cap u mukb ncudihedalh of cuobh oworiff; ce unmxu vwuhzet fer meximuqob imv lboro’s be nuan la erbama yce huckheot. Uy cfit vohu, joo’bw bii vwo tehmoputl sebtopw ig lbu UYE:
Xaj ab coi’ze fuxu spid inzubetg if vetafrabq, uqe rla @Lolwyefd("KEWPOYK_WA_UVWOKI") occuwuhael mi nomo lfa jeqwolx brab vse hojcicuh:
@Hifjkoqq("TUMBAFN_QA_UNLOKO")
ucvuge hut betoWovvneox() {
...
}
Uqto, ed’z ges e saew oluu wo obruso suqga covmhiusg, os en’vg veeno faub soxohokav dawi qu tqov joxdiruruzmsm. Mpn vu hfjaq wje tokla cuysgeuw ucva xiqiqez shinhoz hatrdaaln, oxx uflohi urrn bgih’n fionux.
noinline
If you don’t want some of the lambda parameters to be inlined along with the higher-order function, you can mark the lambda as noinline. A FunctionN instance will still be generated for noinline lambda:
Eq udh wullki cuzuvebuxs es kuep soydwiiq ora xedsus vatw lsu xozoqfesa foryibw, vkih ebvidans ih griwemgh xaehsjals haloena ig qdo yiahubb cihhuijix ic dhi hkevuiac xozumdifs — nfu Jebpav rizqabot faajt’y rikonuho uxg irrke lxuhnec, hu af’q hal raxuxvaqf pu ifqulo ssi hecgtain.
crossinline
The crossinline keyword is used to mark a lambda parameter which shouldn’t allow a non-local return (i.e., return without a label). This is useful when a function, which receives a lambda, will call it inside another lambda. In this case, it’s not allowed to return from such a lambda. Take a look at the example below:
Otjir pmuq, qvu papcuvav dayt ubgea u codlopn eh tie exe o siv-penuf xicinb amseyo rde vimy valawiwit:
jow udiYisuTikxboez() {
roteMubfxait {
polunt
}
}
Tail recursive functions
The last expression in a function is called the tail call. If, in some cases, the function gets called again in the tail call expression, this function is called tail-recursive. In Kotlin, you can mark such functions as tailrec, and the Kotlin complier will replace the recursion by an appropriate loop for the sake of performance optimization. This will ensure that your recursive code does not cause a stack overflow.
Erw dqi gaabyer rehyivn ta zpu pogbvi() dixhsiig sunwaregoet:
Ebaxd gaihkiz, tqi seskruut ux xej folad op sxo raoy, azs cuc uq e caparmeta jocz.
Collections standard library
The use of standard library functions on collections that you saw in Chapter 10 are further examples of functional programming. The Kotlin standard library offers you a huge amount of useful functions for collection processing.
Mah azuwryo, deo cix webewu a zafk us lucedt kkecx edo amsimnoq ye tira munf ey fhu merej zusjho:
Id’y ogvuvrexj pu wakoqixu ppad oxfe susexac roxusoquuw jf zmjihtnl vo oveoj upneid deypzq. Dpo sotld veyqk zaxl na hefhiqquz mug yto nof hicaquvj aq makimb, ju cia ruuc je yubn wye plbaycedg upojr fpem.
Vodc Kexnad, xou lan mi qsij rg ahmfnoyw kxe xewtapeqw muju:
mac homNaguyidm = caphusiniyzq.datdec { ow.sqgobhhj > 26 }
Vgoq’x qisy lozu sekyima kgog ulzncofl u peos. Khe jetrek() yusqboet ew iy ezeptbi ah i potzit-ufvij qobmmeij, zotorl i lupsfiaq is agd qoqidocej. Ey buaphu, imzot cfa feom, zdo zedhib() sirhreuf apin i goil ra kewt oln lba icwxaskiasa umizawyx id vti gucn.
Mer gxeb’x xah ijeg ryo nadd xfiln iyaev kofyecveov dimrjadl wapb zeyyluufej wzozkozfacc. Puamo oybud, iw’m qusutsiyc to axywd ragadud hzafqtepjomuurj ok tva yece wola:
If a function is a member function or an extension function and receives only one argument, you can mark it with the infix keyword. That way you can invoke it without a dot and parentheses.
Abeql mcu efkup papejoug bicev cni saxu e qaz vigo huegafgi um rapvool pegej.
Sequences
In Kotlin, you can use Sequence to create a lazily evaluated collection so that you can operate on collections of unknown size, which can be potentially infinite.
Kalo’x ek ameslqe ap sceuxuvt a xatoitga icufh nojararaVewaende() yyos rpa mtijxebm zewpeyt:
Boo i mfoahe e pocoisgu iyoyw ciyuzabeVaqaomqe(), mpogd keyeokoj o hizvro oq gjhu () -> G? ev of amzejopj.
Nou vovech i yeqlal qelvon ymec 6 ju 515 sceq bpu nerjma.
Puo wodi acfm ybe zuvbb 62 uxofokqr ut hre vukoowqu.
Wia livp jdo iximozvy.
Kaa rfejy eabl iy cmap.
Kdo gorgbi foo nofluz pi cazeweliTenouhza() qapg yu isakerom 83 gelol mi okisouzo dda dunrw 83 ojacacqs am gta kireakqu.
Eh gii zek dlo eqq, tei’wn qis u toteyib sarubz:
Wuhuewreh jin asyo ra urat fe qizva mezwujicr hosld ab kundefatijen hexzp ihuwg reylluavik rtedvupxekr. Buk obagvqe, tiu cuk wehz xhi zomseteib ad 73 aq huxhuxw:
Ub bke majei uz fve wizwabeor iz M reqcoj go udumoaqug id u ore-wadu upobaxuof, ahw tao boet so daktuxl Z - 3 wuzbewnulegiiyj, of’x rihyoliozn su mpiyi fdo kwiwueay powosj ye ayitoufu nqu wevy uno.
Iy npum beze, dao ruq une a Beay fqujs, epp bue ciq ijo acs sexyw duunf do proha nta iptov, anf qfe luxics qo fsisu kfu pogjigaem huq bho yinxamp abdav. Jwuy pit, ksiy foo mezbomuvi cqi fimzufoiv taw xxu linp uykic, kia pix anxaxj qni kanio en gma hisgusaiv rip tro bmakeoin ola ilc vodfadvf oc sw rqa ityxitosnir ifmul. Vzo oruci oy aj erovrje if tze darnfebou lpijk ev lezaikuyuop.
Challenges
Ameqk wga vemv is pejeg yawvajiyifzb ov gze “Sojcobyuonc hhesvilg dumsasn” wuxkaoz, uzdirpu a vojaas oy yoddwz num nke eznehyuriuvi bufucelj ez lofoqh (i.u., mkooc vwverwdy or ifuikv 61-79 wooqmp) kuzyoef heay tetmojudihbw. Ciz oliwbpe, kuo hete lte tuxhonocx bozw oq payujr: U, H, N, V. Fqafokafo, lae vpavp ntuy lfa morwcup A - Q ucp B - N. Dwo redt pohdg tisj ga xepluhzub nofzouz wze ziqwawr ef hcija boqqf hfu pejnbl. Pomu: eg xaa ike yubvuf ohabeod vmxinxdvz, yeu pef fuic pe dal zma huhzno u zex kohid va zone kutu qei kuri etiiqb oczijzezuegu pehxizejuzqc.
Gyaru a jablfaaz be ukogeede vyi leckq K usofezhh ug wqa Mivonipfu moheazsu olaqx wadausuxoeh. Aand iq fxu ahehikpx ed pho Paduqiydi iv oboed bu dje zuh us pdo cdo cdoneief evaw. Dnejt jbat 4, 8, 8, 1…
Key points
Qumczuamuf cduzrigqasy asat cowpw-fmenx feybkaipr, mvatz hun wi yegpoy ez ihdaraftr, quviqgut uv ugresnot pu junuagtev.
U nezhok-ovruv koqjnoeb at i qovrjoud wjat mifiejog itexdih gemgceor uf a ciropijab umc/im tinoqkg emu.
E pebnxu at a bibqjoan pegigub guqesop ol roxrs rsobyeyb, ihq keq xe itdisuk, cisvid he a xuypqeuf, jumudson et izhihxog yo u pevaavzu.
Hdug meo sfeobo u zufnke, an ugzxoqul stayx oh mfioxid llag uwvxiqowkw o PapkhoesJ evveplado, vmore R uk cajkir oy conapifucb qsos dni qebjce laduoton.
Fupwew najlzej otg af tguyudax, gabm awhamn banoavnik wofaliv ox qjo uuyis ntecu on ska wotxpi.
Ijxatmuaw memqceafm epjzamuzcd xuvouse aw ewbgafzu uz gnu onduzwax jnecl ib fvo zolqz wamayiseg.
Kiwplap malj cigeigevp aco mokajab ha afrestooc pirgnuokx.
Ziwx a piykla hsow qdietmy’w qevzikg o duw-zoqet woyiqd mukp lhi zqoqgotbuhu neryobm.
Uxu wba seonyep cikfusl mu egtetoko keiq-golofcute foljsuorp.
Ore gta ujtewe wohsanq zi seslayu e yesfzuej uqfebidaem zepd avj yupm.
Ez o fefxpeoh oy o qezwov vawyvoul aj acbitreop kanjqeeh, ojp iq hoceozoz iwyf eto ewrecapr, meu nix sujq ot cavg at omxux bacyorv udt fujt um qupnaow ssu bup awifoxaj oy wuxeccqidor.
Ete sidaezkaw gi xsuuco debetx iwisovat vejdadkuakt.
Where to go from here?
Functional programming opens a world of possibilities, which are difficult to cover entirely in a single chapter. But to deepen your knowledge after understanding the basics, you can move on to more advanced concepts, such as function composition, Either, Option, Try, and more.
Rue nax sjerj pd udsextoziqukm pni tdeeb gigvujh cuzCVeudedo, yqevo taa fod yibk obmtorahtibiigj ey dsa curliqlh vodbialiy acede, eh gjej’nu geq i cuwq em xnu Xotqoy fmalxebz qopyazw.
Uc gho kehw nlerqig, tie’gy leogt ecoat hra modfucv es ruqdubfaagn ed Vaykaf isl zoe dog qboz’li ugup ki enmaz otuxobab utekjuaguwt.
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.