- Reactive Programming in Kotlin
- Rivu Chakraborty
- 252字
- 2021-07-02 22:26:38
Lambda expressions
Lambda or lambda expressions generally mean anonymous functions, that is, functions without names. You can also say a lambda expression is a function, but not every function is a lambda expression. Not every programming language provides support for lambda expressions, for instance, Java didn't have it until Java 8. The implementations of lambda expressions are also different in respect to languages. Kotlin has good support for lambda expressions and implementing them in Kotlin is quite easy and natural. Let's now take a look at how lambda expressions work in Kotlin:
fun main(args: Array<String>) { val sum = { x: Int, y: Int -> x + y } // (1) println("Sum ${sum(12,14)}")// (2) val anonymousMult = {x: Int -> (Random().nextInt(15)+1) * x}
// (3) println("random output ${anonymousMult(2)}")// (4) }
In the preceding program, in comment (1), we declare a lambda expression that will add two numbers and return the sum as result; in comment (2), we call that function and print it; in comment (3), we declare another lambda that will multiply a random number bound to 15 with the value x passed to it and return the result; in comment (4), we, again, print it. Both the lambda expressions are actually functions, but without any function name; thus they are also referred to as an anonymous function. If you compare with Java, Java has a feature of anonymous class, but included lambda/anonymous functions only after Java 8.
If you are curious about the output, then refer to the following screenshot:

- 云計(jì)算服務(wù)保障體系
- 醫(yī)療大數(shù)據(jù)挖掘與可視化
- 數(shù)據(jù)革命:大數(shù)據(jù)價(jià)值實(shí)現(xiàn)方法、技術(shù)與案例
- “互聯(lián)網(wǎng)+”時(shí)代立體化計(jì)算機(jī)組
- MATLAB Graphics and Data Visualization Cookbook
- 圖數(shù)據(jù)實(shí)戰(zhàn):用圖思維和圖技術(shù)解決復(fù)雜問題
- SQL應(yīng)用及誤區(qū)分析
- Unreal Engine Virtual Reality Quick Start Guide
- 貫通SQL Server 2008數(shù)據(jù)庫(kù)系統(tǒng)開發(fā)
- 大數(shù)據(jù)計(jì)算系統(tǒng)原理、技術(shù)與應(yīng)用
- ECharts數(shù)據(jù)可視化:入門、實(shí)戰(zhàn)與進(jìn)階
- 成功之路:ORACLE 11g學(xué)習(xí)筆記
- 量化投資:交易模型開發(fā)與數(shù)據(jù)挖掘
- 一本書講透數(shù)據(jù)治理:戰(zhàn)略、方法、工具與實(shí)踐
- Access數(shù)據(jù)庫(kù)教程(2010版)