Scala – Lambda Function

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

Lambda Expressions in Scala

 

A 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.

Lambda expressions, also known as anonymous functions or function literals, are a fundamental feature of functional programming in Scala. A lambda expression is a concise way to define a function without explicitly specifying a name. Instead, it defines the function’s behavior inline, often as a parameter to another function or as a standalone expression.

In Scala, lambda expressions are created using the => syntax, which separates the function parameters from the function body. For example, (x: Int) => x * 2 is a lambda expression that takes an integer x as input and returns x multiplied by 2.

Lambda expressions are commonly used with higher-order functions like map, filter, and reduce to process collections in a functional style. They enable functional programming paradigms such as immutability and referential transparency by treating functions as first-class citizens.

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)

0
0

Quick Support

image image