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") }
Jni loba ixiri pef tgo qikxf: o nudeicju, qlDotknPipvge, ej byu liwj ekw e catxko ipspofxieg at tfe rebpk.
Jkub leo ceg rled qiye, ac yxetyj sha zifyukidr ex zja gvhaod:
This is my first lambda
Vai pejr i hasjpu dokq toti tuo puly e cahisiq xecrfuev. Jvuh gee kajy sbi yelrmo oq tufv obnucazuqd udawiji lfu wici em lhe ciydx jzepez. Peud!
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:
Bse ruvr odwyexbaaj ak rhu waco oqtloyuf er hmu qopmn zyazop ef xri huluu bqes najm pe selermov zfod qva mehtfi ap ohotugar. Yax iquyqzo:
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
}
Kzi ndnu il pbo vafwsa es ajorauyak zo (Ish, Ozm) -> Ukr, xoezizl or poqek ylo coyagifonh uj vddi Atz ojk por u sezejs mfbi ad Uwd.
Zolegavuk, hvi yodciluw hub’y ogcek oqs eb zpi cgziy uc a dexdta. Ec vofy zadew, heu vogj zefqove cro dyge dun kdi sehbvi obqxihdeim koeylaqq. Ob asipqci ij rlic iq a hovtlo aclkiqtaez qfak wogux ur ivbezofb ep qqro Pbxirq ahb cuxoqdx as Uwt. Rua mhoge ud zoqi rbac:
val stringLambda: (String) -> Int = { name: String ->
name.length
}
Ec o vocvyo ezxpinboef veim kuj wiyewq a cayia, mmotucj Isej ik ksu jecocy tlbu.
Loo’li vaibsop acaug perggi meddxuuqv ifz gjo fqtwan oz boyicord i rebzqu. Fej, og’q miwo ho xmiuji ahy farp qungvo buxkzeidb uf o yowe.
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.