Open In App

Lambda Expression in Scala

Last Updated : 28 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Lambda Expression refers to an expression that uses an anonymous function instead of variable or value. Lambda expressions are more convenient when we have a simple function to be used in one place. These expressions are faster and more expressive than defining a whole function. We can make our lambda expressions reusable for any kind of transformations. It can iterate over a collection of objects and perform some kind of transformation to them.
Syntax:

val lambda_exp = (variable:Type) => Transformation_Expression

Example:

// lambda expression to find double of x
val ex = (x:Int) => x + x
Working With Lambda Expressions
  • We can pass values to a lambda just like a normal function call.
    Example :




    // Scala program to show
    // working of lambda expression
      
    // Creating object
    object GfG
    {
          
    // Main method
    def main(args:Array[String])
        // lambda expression
        val ex1 = (x:Int) => x + 2
      
        // with multiple parameters
        val ex2 = (x:Int, y:Int) => x * y
          
        println(ex1(7))
        println(ex2(2, 3))
    }
    }

    
    

    Output:

    9
    6
  • To apply transformation to any collection, we generally use map() function. It is a higher-order function where we can pass our lambda as a parameter in order to transform every element of the collection according to the definition of our lambda expression.
    Example :




    // Scala program to apply
    // transformation on collection
      
    // Creating object
    object GfG
    {
          
    // Main method
    def main(args:Array[String])
    {
        // list of numbers
        val l = List(1, 1, 2, 3, 5, 8)
      
        // squaring each element of the list
        val res = l.map( (x:Int) => x * x )
      
    /* OR
    val res = l.map( x=> x * x )
    */
        println(res)
    }
    }

    
    

    Output:

    List(1, 1, 4, 9, 25, 64)

    We can see that the defined anonymous function to perform the square operation is not reusable.

  • We are passing it as an argument. However, we can make it reusable and may use it with different collections.
    Example :




    // Scala program to apply
    // transformation on collection
      
    // Creating object
    object GfG
    {
        // Main method
        def main(args:Array[String])
        {
            // list of numbers
            val l1 = List(1, 1, 2, 3, 5, 8)
            val l2 = List(13, 21, 34)
          
            // reusable lambda
            val func = (x:Int) => x * x
      
            // squaring each element of the lists
            val res1 = l1.map( func )
            val res2 = l2.map( func )
          
            println(res1)
            println(res2)
        }
    }

    
    

    Output:

    List(1, 1, 4, 9, 25, 64)
    List(169, 441, 1156)
  • A lambda can also be used as a parameter to a function.
    Example :




    // Scala program to pass lambda
    // as parameter to a function
      
    // Creating object
    object GfG
    {
      
        // transform function with integer x and 
        // function f as parameter
        // f accepts Int and returns Double
        def transform( x:Int, f:Int => Double) 
        =
        f(x)
      
        // Main method
        def main(args:Array[String])
        {
          
            // lambda is passed to f:Int => Double
            val res = transform(2, r => 3.14 * r * r)
      
            println(res)
    }
    }

    
    

    Output:

    12.56

    In above example, transform function accepts integer x and function f, applies the transformation to x defined by f. Lambda passed as the parameter in function call returns Double type. Therefore, parameter f must obey the lambda definition.

  • We can perform the same task on any collection as well. In case of collections, the only change we need to make in transform function is using map function to apply transformation defined by f to every element of the list l.
    Example :




    // Scala program to pass lambda
    // as parameter to a function
      
    // Creating object
    object GfG
    {
      
        // transform function with integer list l and 
        // function f as parameter
        // f accepts Int and returns Double
        def transform( l:List[Int], f:Int => Double) 
        =
        l.map(f)
      
        // Main method
        def main(args:Array[String])
        {
            // lambda is passed to f:Int => Double
            val res = transform(List(1, 2, 3), r => 3.14 * r * r)
            println(res)
        }
    }

    
    

    Output:

    List(3.14, 12.56, 28.259999999999998)


Previous Article
Next Article

Similar Reads

Scala - Expression that Can't be Reduced to a Value
Scala adheres to expression-centric philosophy design, where anything can be evaluated to produce value. This is a way to be more expressive and follow the principles of functional programming. Substitution Model in ScalaThe substitution model is a fundamental concept in programming. It provides a way to understand how expressions are evaluated. In
2 min read
Scala short <(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short <(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &() method with example
The &() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int <(x: Char) method with example
The <(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).<(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int <=(x: Double) method with example
The <=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).<=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int <=(x: Byte) method with example
The <=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).<=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Parameterless Method in Scala
Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle. Exa
2 min read
Scala short /(x: Short): Int
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The /(x: Short) method is utilized to return a result of the quotient operation on the specified Short value by the x. Method Definition: def /(x: Short): Int Return Type: It returns quotient with value and x. Example #1: // Scala program of Sho
1 min read
Scala List isEmpty Operation with example
The isEmpty operation is utilized to check if the stated list is empty or not. Syntax: m1.isEmpty Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false. Example #1: // Scala program of isEmpty() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set dropRight() method with example
The dropRight() is utilized to return all elements except last 'n' elements. Method Definition: def dropRight(n: Int): Set[A] Return Type: It returns a set containing all elements except last 'n' elements. Example #1: // Scala program of dropRight() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating
1 min read
Scala Set equals() method with example
The equals() method is utilized to check whether the two sets have the same elements or not. Method Definition: def equals(that: Any): Boolean Return Type: It returns true if the elements of both the sets are same else it returns false. Example #1: // Scala program of equals() // method // Creating object object GfG { // Main method def main(args:A
1 min read
Scala Set drop() method with example
The drop() method is utilized to delete the first ‘n’ elements or to return all elements except first 'n' elements. Method Definition: def drop(n: Int): Set[A]] Return Type: It returns all elements except first 'n' elements. Example #1: // Scala program of drop() // method // Creating object object GfG { // Main method def main(args:Array[String])
1 min read
Scala Set dropWhile() method with example
The dropWhile() method is utilized to drop the longest prefix of elements from the set that satisfies the stated condition. Method Definition: def dropWhile(p: (A) => Boolean): Set[A] Return Type: It returns a set containing all the elements after dropping the longest prefix of elements from the set that satisfies the stated condition. Example #
1 min read
Article Tags :