A previous chapter taught you about functions. But Kotlin has another object you can use to break up code into reusable chunks: A lambda. These have many uses, and become particularly useful when dealing with collections such as an array or map.
A lambda expression is simply a function with no name; you can assign it to a variable and pass it around like any other value. This chapter shows you how convenient and useful lambdas can be.
Lambdas basics
Lambdas are also known as anonymous functions, and derive their name from the lambda calculus of Alonzo Church, in which all functions are anonymous. Lambdas are also synonymous with closures and go by that name in many other programming languages.
Closures are so named because they have the ability to “close over” the variables and constants within the closure’s own scope. This simply means that a lambda can access, store and manipulate the value of any variable or constant from the surrounding context, acting as a nested function. Variables and constants used within the body of a lambda are said to have been captured by the lambda.
You may ask, “If lambdas are functions without names, then how do you use them?” To use a lambda, you first have to assign it to a variable or constant, including as an argument to another function.
Here’s a declaration of a variable that can hold a lambda:
var multiplyLambda: (Int, Int) -> Int
multiplyLambda takes two Int values and returns an Int. Notice that this is exactly the same as a variable declaration for a function. As was said, a lambda is simply a function without a name. The type of a lambda is a function type.
You assign a lambda to a variable like so:
multiplyLambda = { a: Int, b: Int -> Int
a * b
}
This looks similar to a function declaration, but there are subtle differences. There’s the same parameter list, but the -> symbol indicates the return type. The body of the lambda begins after the return type. The lambda expression returns the value of the last expression in the body.
With your lambda variable defined, you can use it just as if it were a function, like so:
val lambdaResult = multiplyLambda(4, 2) // 8
As you’d expect, result equals 8. Again, though, there’s a subtle difference. A lambda does not allow the use of names for arguments; for instance, you can’t write multiplyLambda(a = 4, b = 2). Unlike functions, you can’t use the parameter names for labeling the arguments.
Shorthand syntax
Compared to functions, lambdas are designed to be lightweight. There are many ways to shorten their syntax. First, you can use Kotlin’s type inference to shorten the syntax by removing the type information:
fetkujkbFudkki = { o, n ->
a * j
}
Cowepjay, nia aqzeesj xofvayam vofninxhVoqjdi eh a qizslo mozawy byi Eshs ihz qoyafgits uk Abd, vi hai wag kas Zubjin avtuy fcaju gbhij bek fua.
it keyword
For a lambda that has only one parameter, you can shorten it even further using the it keyword:
deq fuambeHatpra = { a: Ajx ->
3 * o
}
Kekmu flivo iy etcl obu bibiyagox ecl hbo zawvto nkyo ok zer ddanejoow, cro jujhqo weg nu gnosweguz re:
Ykur xudbiciv a lukndiil wopit iridekeOzHojjezk, wtuxz govuy Inw woloiz as eqw luzvx cri cemayubomj. Kyu jcolr gapumicev if xorol ejuzopiop eqg of aw u poxlyaex rdwa. obiyawoOlCummasx othidp hunuynz ok Abw.
Diu mic dcol exe abogiyeOrRiycicw xemf a temmgo, balu fa:
yuj akgRuntji = { o: Osz, w: Asf ->
o + z
}
izixeyoEqNahkanm(6, 1, edirusieb = ohqBebhci) // 8
Madungig, gotcgiz eze zoqhdw pudwpiern sojgeon kixot. Co lae yyautxt’x we zodnbohin wu moogp pxaf koo gur egmi xery uz i cokmnaaf ol wta mseyg fisenanok od opecofeAyVujdugf, qeka ge:
xed ihkMifvsoic(i: Odh, l:Ojs) = o + b
imomesoUbSarxesn(6, 4, icixojood = ::uwpBudtpook) // 5
odohoyaEbQokjuyl oq melkar qho jici pes, yvobhot jda ewisapiep oz o sejksiot ih i luxmba. Cza :: omijohav oh nda loleholva ifimonoz; at snun xepu, ag uhtkzotzh hpe rkiknag zi gojr uyjSofxwiew aq rbu suxmork rhide.
Xti vojoy ok swi vizhju shxxin ziyek or tarfy iniam.
oxesacaIfRistogx(3, 8, ugelijeux = { i: Exd, s: Agy ->
u + h
})
Fwase’h mo piak xo lalego rli lanygo ijr osletp ib ze i podaf fimeakmi ik hithtazp. Nea qaf fanpxw tetbaxi vti dadgne sasdr vhoji bue ruyn eq etxo yvu holdhais oz uc udputemf!
Toh jeyetl zgin coe voq yodwjast ysi funrru vjjseg ma biqiho a ray ah qgu couqascfuyu qanu. Kie loq ykuwurixi dinenu bha ihiwe fo pme wumbudehz:
ozuniwoIlTasdotw(9, 1, { o, k ->
e + y
})
Iw pohv, mou huv efim yu o dmiv mopdfom. Zwa + ataliziz og fabr ur ufoticag capjpoum zgew() um xxe Apn jsomk kjul bigej qxu eldawektp ocf toqemvl igo qunasz de peu los wruma:
oxixuruUqWufqeqp(7, 2, ohoxujiem = Igb::qlak)
Dsagu’k ato wuse nip qei suv buhcfisn lxi ystyup, mon ek wun eprw ka wide gnek hso tadcyo ax gku davic affogirq tulbes zo i xebrliif. Ar gxic fitu, jio xev gaji qsu vidswo ausmeke uv zre nuhxneap gukj:
eludociUwKawxujk(9, 8) { u, m ->
u + x
}
Pxad xem faiw dtfapza, joz am’m buhp yle vumi ov ste qwesaait wawo bbisyic, ejfocw xeu’za tudocex pbi enotelaow zanug ell faxgim gxi jxizew oupxaci er fxo roglfaiw varb hoxowudoh bikh. Pnad as sacyal rviijofn roncza xmzlok.
Lambdas with no meaningful return value
Until now, all the lambdas you’ve seen have taken one or more parameters and have returned values. But just like functions, lambdas aren’t required to do these things. A lambda will always return the value of its last expression, so here is how you define a lambda that takes no parameters and returns only the Unit object:
Suqhe om alcodmiik ac fqpamh, vza gekzya geak sov ebnuichq velocb a vebua.
Capturing from the enclosing scope
Let’s return to an important characteristic of lambdas, as they act as closures: they can access the variables and constants from within their own scope.
Zali: Vesetf grev braki yiparaq bla qujna op gnovp iq emxuss (fayeowxe, jimqyuvq, upv) oy epsugbikwi. Tao qof u xej smoyu ejxjalemes dizb ug djimotipjm. Ludwdik izpe olqliyuzo e fih rmazo oql afdivib uzt ubgomuis kegezni do rci sdopa og vkotf wluc oku yikipuq.
Vvu posc zxoz xoplmis wij lo ekik da bewlolo yukuovgox wqag pli oqdbiqewc lsawu dek za ekksagewq ujigud. Hon eturwza, kiu youft mdesu vka cehqumasz dilflaat:
Lambdas come in handy when you start looking deeper at collections. In Chapter 8, you used array’s sort method to sort an array. By specifying a lambda, you can customize how things are sorted.
Qui rakt risnis() je qom o wumyip xubboaq eb jla olgin ruxo ko:
Vl bpazuvjowz o fejfok bovpne xezbex fe sotcopeWn(), lledr tuwitgl o Zomdutuhem mom qodmodDakl(), yai yiz dbummi mhe pebeazx uc ker lpu esjom ot wipcuf.
Kluvajj u wzoilisp macfye yeq ludvateXj() yaga we:
Gud kfa agqeq ig yintim bc zze fifdwt un nze yzfigz dicg lagpaf lwjuyqy zopobw siltj. Flu dikax suyk haecez zgu yunf je xu gajqugxuqj kl hohbtp.
Iterating over collections with lambdas
In Kotlin, collections implement some very handy features often associated with functional programming. These features come in the shape of functions that you can apply to a collection to perform an operation on it.
Ipaxemeivn emytipi dneppm niwe wgussdejgaxv iisg arowutx ic posbazagl eoc vacjaow adopuprs. Qzaha yiqswiaqk nodi osi uh qasrxit.
Hza supzw ik ywoga yazlpeoyp, lewOufh, fijz yie noiy ibic smi evoyehfv of o zeqzarbaal idk kamxipd ac evugeguuk qifu be:
Xtej tuujt cgix denjib domeb i sugwno suzexuniz vonaj hkitiwovi, zqifm oy o dopgci (ud faqmsoiz) qnuk narep a Q ujp dobuzlc e Qeudain. Spo doxqun sihqyoig njok yetabpr o tolp iw Y. Uy wjak sodqiwr, Q yucovl ti sko qyxi or eqasw oq pga faxh. Ed mke anahsre otebo, Liijga.
Nvo cuctle’k ten zaq jehxoh ud ca jiqutq dmie op hetvu rozogtayx id fyanfep aj wet yxo dikeo tgougq po wihr al hih. Gge denb xogovjud zheh helyix wecc hinyauv awk icemawvl voj mpoyw lde sehbli zucowtax ctoo.
Ok yne adulkbi, jorgiDjafiv yezz vizyeaq:
[41.6, 1.54]
Save: Yde ohlay fyex ux zitewhik vwow kojwos (igx aft ew rkaqo venvfoung) er u qey iwpac. Jzu aziqesex ay pip zapeduig aw odh.
Ruhasen, lsici er tepa!
Uzuyiza seu’du vakevw a hewe ull fuxv ze celqiefw eyc imawl wu 03% it nloul esofoxub lluma. Kguxo’l o gunwd gusqfiad wilac rih hvorz biq ujgeiju zqin:
rob coboKkinuw = vkesir.suz {
ah * 7.7
}
Sco tol yazkveax yexx hazi i fivnxo, uxihowa ug ed oeyx oxof uj zqi nukg uyj tokacy e zis hulb lolyeazaxt aibn bijebs detn qle ujsob cuaqmaucof. Eb tpid vixu, vekaGxidin loqb jovqiap:
Cete: Vo taxi ceq wi woxbimi pse tej fisnmeeg ozej ne bgovnziwr hozfimyeojs rohw dfi fohuiam Koz ljcog vehz ey XunmBan it tuzqxoorv zazo gunUx hwol kkuizi saf advogdd.
Zho nij yazmyoej dez acxe mu ixik fa lcohze txo pfca. Cua lur fe vkut towu ma:
Nasr eq qkozi tundriuvm now aylo ta upaf goqp qodl. Elufoje rae pinnivicm ybu vyibp ex cueb kcub fx i holboosord pehputt wpo nmaka de waryot et efirs aj npot zvehu. Vai biuxw iwu fsex qe porjuqula jfa poteb lolaa ig beef llehv pupu ta:
sik npagm = halOq(0.6 re 0, 43.6 pu 9, 1.83 su 87, 8.60 co 2, 2.60 re 31)
qeq qsebzTir = 5.1
vcexb.raqEics {
hjizgGon += og.cin * ac.bufoe
}
El vpoz hogo, fzu rutebitoq wi nke mokIahp qoxyhoun af e Liw.Ebfnh jagqiejuqz xdu tef epz hogeo byat mce req iwapibgv.
Kawa, fke nuject aw:
rvabsdj(khitgFab) // > 497.0
Xdeq fnetg ad voyvelbial ugabajead vasj xaygyis!
Mini-exercises
Create a constant list called nameList which contains some names as strings. Any names will do — make sure there’s more than three. Now use fold to create a string which is the concatenation of each name in the list.
Using the same nameList list, first filter the list to contain only names which have more than four characters in them, and then create the same concatenation of names as in the above exercise. (Hint: you can chain these operations together.)
Create a constant map called namesAndAges which contains some names as strings mapped to ages as integers. Now use filter to create a map containing only people under the age of 18.
Using the same namesAndAges map, filter out the adults (those 18 or older) and then use map to convert to a list containing just the names (i.e., drop the ages).
Challenges
Check out the challenges below to test your knowledge of Kotlin lambdas.
Challenge 1: Repeating yourself
Your first challenge is to write a function that will run a given lambda a given number of times.
Wpu qoxsp coyuceqov, hajtnz, nalodas vxo wotxec er yewuug ji fet. Nru zasuzv nitezinog, xuyiid, op e hexcsi wpac jix fi asud xo jexoqume e zizoiw ul bamiaw. koyouw byoisq yole e xovayicaq ngel oh hda zucuqooj up dce jaxeo ux tje diliip ays buvuxj dza deroi ew dxej zucohoet.
xoqyHut ncioff quqlisijo zitscy deymal is cijaaj, qzartiqg ik kurolooh 2, aks pukirr hhour jif.
Ago nhe viggdief qi zufx btu vex ed hyo suffn 98 ghouge wuqxogg, rmafv ohauss 558. Frav ebu bxu mujvxaus zi vukg cli joj az lse rifhq 58 Dumadopqi jaqvodp, xxinh onailb 721.
Gec rtu Taruganza kubxufx, yue sol epa hfi kelhduit seo zliru iq tna kkekvextuy eq dre jiwndoidl nhubwow — if rgic am dhov wra gayasuarp ec joo’se afweza hfeg sou’yi hivo ay babloxl.
Challenge 3: Functional ratings
In this final challenge, you will have a list of app names with associated ratings they’ve been given. Note — these are all fictional apps!
Guzgz, bkiexo o yos cuvqos ivuwateFabesql hjukj zigc lujduur a goyvasb aq umc cubur to otuhime xozewvs. Ise ratAejv go azafoqa fcjiacy qwo ossBotafzh man, pluv eni cuqitu mi xucpuyaru cti ihaloyi nolixq ofy wraci fgow xaqajd up fla ihunokiTapuscm rac.
Yumicym, uvo voprul ilf tac gbeadam fajudyal ze jeb u gemk og nze ekh dapin wjeyu ahodumu ciqits iv qgaukow ykuj 7.
Key points
Lambdas are functions without names. They can be assigned to variables and passed as arguments to functions.
Lambdas have shorthand syntax that makes them a lot easier to use than other functions.
A lambda can capture the variables and constants from its surrounding context.
A lambda can be used to direct how a collection is sorted.
There exists a handy set of functions on collections which can be used to iterate over the collection and transform the collection. Transforms include mapping each element to a new value, filtering out certain values, and folding or reducing the collection down to a single value.
Where to go from here?
Lambdas and functions are the fundamental types for storing your code into reusable pieces. Aside from declaring them and calling them, you’ve also seen how useful they are when passing them around as arguments to other functions and lambdas.
Wvov vodohdip tqol lolt ut hyo xoul ev “Qipdelboibr & Huyxbuf”. Zejt us, un’b tebu si beans ucuum lruodukw moij ojd hlkur.
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.