Monday, 31 August 2020

Scala: Lambda Expressions

‘Lambda Expression’ is a block of statements used to perform a task. Once you define a named lambda expression, you can call it any number of times.


Lambda Expressions in Scala are objects.

a.   You can store a lambda expression in a variable.

b.   You can pass a lambda expression as an argument to other function

c.    You can return a lambda expression from other function

 

How to define a lambda expression?

Syntax

(param1, param2…paramN) => {

 

}: returnType

 

If you omit the returnType, Scala infers it.

 

Example 1: Lambda expression to calculate sum of two integers.

scala> val sum = (a: Int, b:Int) => {
     |  a + b
     | }
val sum: (Int, Int) => Int = $Lambda$1200/374184770@67026899

Above snippet define a lambda expression that takes two arguments and returns the sum of these two arguments. Since a lambda expression is an object, I assigned it to a variable ‘sum’.

 

I can call the lambda expression using the variable ‘sum’ as below.

sum(10, 20)
scala> sum(10, 20)
val res23: Int = 30
You can even specify the return type of the lambda expression while defining it.
scala> val sum = (a: Int, b:Int) =>  {
     |  a + b
     | }: Int
val sum: (Int, Int) => Int = $Lambda$1206/1771132309@269e7adb

Example 2: Lambda expression that prints a welcome message.

scala> val welcomeMessage = (name : String) => {
     |    println(s"Hello $name")
     | } 
val welcomeMessage: String => Unit = $Lambda$1204/1900323213@6b3f6903

scala> welcomeMessage("Krishna")
Hello Krishna
If a Lambda expression does not return any value, you should specify it using ‘Unit’. If you do not specify the return type of a lambda expression, Scala infers it automatically.
scala> val welcomeMessage = (name : String) => {
     |    println(s"Hello $name")
     | } : Unit
val welcomeMessage: String => Unit = $Lambda$1207/139989607@188f3449


Previous                                                    Next                                                    Home

No comments:

Post a Comment