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

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:

主站蜘蛛池模板: 镇平县| 和林格尔县| 平安县| 长乐市| 禹城市| 灵璧县| 凤阳县| 仁怀市| 囊谦县| 板桥市| 铜陵市| 阿图什市| 卢湾区| 四平市| 南投县| 离岛区| 清远市| 射阳县| 丹阳市| 莲花县| 内黄县| 察哈| 岳西县| 黄梅县| 图木舒克市| 高唐县| 曲松县| 满洲里市| 黎川县| 甘肃省| 通榆县| 临清市| 石棉县| 米林县| 离岛区| 沙田区| 舟曲县| 大厂| 兴海县| 渭源县| 深水埗区|