### Scala – Lambda Function

• date 27th April, 2021 |
• by Prwatech |

Lambda Expression is an expression that uses an Anonymous function rather than value or variable. Lambda expressions are more helpful when there is a simple function to be utilized in one place. These expressions are quicker and more expressive than characterizing an entire function. We can make our lambda expressions reusable for any sort of transformations.

use case 1:

``````object prwatech {
// Main method
def main(args:Array[String])
{
// lambda expression
val ex1 = (x:Int) => x + 4

// with multiple parameters
val ex2 = (x:Int, y:Int) => x * y

println(ex1(7))
println(ex2(2, 3))
}
}``````

output:

11
6

use case 2:

``````object eduprwa {
def main(args:Array[String])
{
// list of numbers
val a = List(1, 2, 3, 4, 5, 6, 7)
// squaring each element of the list
val res = a.map( (x:Int) => x * x )
/* OR
val res = a.map( x=> x * x )
*/
println(res)
}
}``````

output:

val a = List(1, 2, 3, 4, 5, 6, 7)

use case 3:

``````// Scala program to apply
// transformation on collection
object lambda {
// Main method
def main(args:Array[String])
{
// list of numbers
val x1 = List(1, 2, 0, 6, 7, 8)
val x2 = List(10, 20, 30)
// reusable lambda
val func = (x:Int) => x * x

// squaring each element of the lists
val res1 = x1.map( func )
val res2 = x2.map( func )

println(res1)
println(res2)
}
}``````

output:

List(1, 4, 0, 36, 49, 64)
List(100, 400, 900)

### Quick Support  