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

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:

主站蜘蛛池模板: 九寨沟县| 平利县| 永修县| 淮北市| 甘孜| 泉州市| 灵武市| 姜堰市| 社会| 峡江县| 康保县| 郯城县| 新密市| 凭祥市| 南宫市| 绍兴县| 洪江市| 沅江市| 清远市| 海晏县| 司法| 泉州市| 交口县| 保定市| 盐边县| 田阳县| 西平县| 顺昌县| 威信县| 泌阳县| 托克托县| 瑞丽市| 射洪县| 涟水县| 习水县| 安泽县| 鄢陵县| 和政县| 赣榆县| 从江县| 依兰县|