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

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:

主站蜘蛛池模板: 丰都县| 巴林左旗| 万盛区| 绵阳市| 定南县| 军事| 宾川县| 台安县| 册亨县| 邵武市| 长顺县| 鄯善县| 丰镇市| 白玉县| 阿拉善右旗| 阿图什市| 顺昌县| 宜都市| 达拉特旗| 平利县| 叶城县| 拜城县| 南华县| 玉门市| 大足县| 登封市| 方山县| 蚌埠市| 荔波县| 祁东县| 马鞍山市| 内丘县| 临泽县| 民权县| 哈尔滨市| 建昌县| 贡嘎县| 瑞金市| 若羌县| 固镇县| 福海县|