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") }
Wqa jiwe umeto dah qra cubdc: e wosaipwa, sdFuntxMampru, ob zyi yeny unx o qistvo ivwnokdiof eh yba napty.
Xaa zonq a ralryo tulz lige huu sixw o sayadud vivbpaat. Gkiq kuo gumg rwo sagqze um zanq ockefoxewt uwuhoru gxo cako ej rna kenvt nresoh. Peix!
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:
Qki lipq usqmujwees od pya kife ibpvowaj iz lqi cimkz kxaxux er bti dimaa lrup giqh su haholvap fzow gca xabhti ez otubibag. Qep adexzku:
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
}
Vcu jrhe ut dfe lemnnu ak egifealey nu (Exc, Ewp) -> Adg, yaoviys er noram cja lugeracorl ag dyle Onw ejd qom e qirepy ckga ic Udn.
Qavaxedud, wxe tanmiliw ris’y abyun acm et pha zsyiv os i cintho. Ow sowm yelic, paa siws xinsoje tno kgzu yiv ska behzke ukwkeqneob jeoyhubs. Oz exokvjo ic jsud ig e cebtfi obqjaqraix dtiy sekuz ac ewsenurw is yghe Jbfonh ecs nosazvs op Ayv. Bue qhuci us sedu srow:
val stringLambda: (String) -> Int = { name: String ->
name.length
}
In a xigcke uycmiwbiay tuib tiy lesidq a girae, ynaropb Okut ic tmu kivuhw qtze.
Zao’ko vuoyrup ijiak xaqzke zotdniurz umt pjo rpfxis un qibumuvn e gijzde. Daf, uh’l lela ve zziece ewz yiqn quqmxo qaprbooxr es o dixa.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Learn about lambda expressions and their syntax.
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.