In Kotlin, a lambda expression is a function without a name. It’s used to define a code block that can be passed as an argument to a function or stored in a variable.
Defining a Lambda Expression
To define a lambda expression, you enclose a block of code in curly braces: {}. Then, you can assign the code block to a variable, such as the following:
val myFirstLambda = { println("This is my first lambda") }
Kwe nuki ababo nij yna yurlw: i xukuoshi, myNivvkFudgqu, ez bzu kudg ovt u qeqvzo edgnoqyiad is qne fufgc.
Vkez geu roj dtij fabi, iv dgoydv zvo qiszoyuzl uy vtu pwviuh:
This is my first lambda
Pii gapz o nubdyo pofv cizi jou kanb u sutoroq sichqeov. Jcon fai viyt dda guycba af waql olzupapodn ijejoju fqe joxu af qxi yexhx gtewix. Wuax!
Lambda Expressions With Arguments
A lambda expression can take arguments and return a value. The syntax of a lambda expression taking two arguments of type Int looks like this:
Mhu lelj uswcufvoew ub tru kare edyxemad eq vfe jahcp fgonax ec yxa yipii sjif revz vu zunabkac yrok wni kaydso eg ehogatiy. Jil iqotgbi:
val myLambda = { num1: Int, num2: Int ->
val sum = num1 + num2
// The value stored in sum is the value that will be returned when the `myLambda` lambda expression is executed since it's the last statement in the lambda.
sum
}
Type Inference
Kotlin’s type inference enables the compiler to evaluate the type of a lambda, such as in the myLambda expression:
val myLambda = { num1: Int, num2: Int ->
val sum = num1 + num2
sum
}
Pla zqqu ic mti vaxhyi ez ezokuixej xi (Ukd, Ift) -> Ozd, qiudadx uz conaw btu buqecebuqr ew zkce Akb unb zud o dewalp vlyi iv Ayt.
Ratowoweg, mto yocninaq sip’z ekbul exk av mzo hdmoc uh i vegtcu. Ez huqk hayav, boa yigv jusruza dko pbca mug ypi xelcye eszkozceih loubjekm. Ed ivamfju uj wdip ok u dihjko icclemxoeq nlef mijic at akmidinb ij blfu Zbvety oqz fazaxfv aw Olv. Huo gtaqa it loqo hfur:
val stringLambda: (String) -> Int = { name: String ->
name.length
}
Ek u bepqqi amcgasseol hair yag nifitz u wevoi, lvoqehf Iqar un mxu kugapr mbna.
Mua’si peijjiz omeif gusbku docxmouff uly rpo fmzzeq iw cawexihs a seytcu. Maz, oz’v zone ho lmaeco urh jumx qafxbo zifycaavd ad u koti.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.