官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 东明县| 万载县| 华亭县| 铁力市| 呼和浩特市| 河池市| 武陟县| 西乌珠穆沁旗| 江阴市| 涿州市| 西和县| 衡山县| 平武县| 龙岩市| 托里县| 烟台市| 彩票| 商河县| 沙河市| 鲁山县| 洛川县| 新沂市| 平原县| 渭源县| 新源县| 务川| 进贤县| 定安县| 商洛市| 洛南县| 石楼县| 东源县| 桐城市| 广德县| 嘉祥县| 芦溪县| 尼勒克县| 吴旗县| 天峨县| 驻马店市| 黄石市|