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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.157