Home » Scala language

Anonymous functions in Scala

Anonymous functions also known as function literals are functions that only have definitions and do not have a name are anonymous functions. In this tutorial, we will learn how Scala anonymous functions are defined and used in a Scala code?
Submitted by Shivang Yadav, on June 28, 2019

Anonymous functions in Scala

A function with no name is an anonymous function which is also known as function literal. This type of functions is used when the user wants to create an inline function.

Syntax:

    1)    (x: Int , y:Int) => x + y
    2)    (_:Int) + (_:Int)

Syntax explanation:

There are two syntaxes to define an anonymous function in Scala. First one uses a transformer ( => ) to the anonymous function. The second code directly uses a wildcard ( _ ) and directly uses definition.

An anonymous function can have arguments and may not have arguments in its definition.

Anonymous function with parameter

It defines the function arguments in its definition. There are direct function definitions and it can be called using the variable name with which it is defined.

Example:

object Main  
{ 
    def main(args: Array[String])  
    { 
        var mySum1 = (number1 : Int , number2 : Int ) => number1 + number2
        var mySum2 = (_:Int) + (_:Int) 
        println("Anonymous Functions Example Code :")
        println("Sum of 5 and 12 is " + mySum1( 5, 12)) 
        println("Sum of 15 and 21 is " + mySum2( 15, 21)) 
    } 
} 

Output

Anonymous Functions Example Code :
Sum of 5 and 12 is 17
Sum of 15 and 21 is 36

Anonymous function without parameter

It defines a function without any arguments in its definition. A variable is used to define the anonymous function. But this one has no arguments in its call.

Example:

object Main  
{ 
    def main(args: Array[String])  
    { 
        var myfun1 = () => {"Hello! This is Include Help..."} 
        println(myfun1()) 
        def myfunction(fun:(String, String)=> String) = 
        { 
            fun("Hello", "User") 
        } 
        val f1 = myfunction((str1: String, 
                    str2: String) => str1 + str2) 
        val f2 = myfunction(_ + _) 
        println(f1) 
        println(f2) 
    } 
}

Output

Hello! This is Include Help...
HelloUser
HelloUser






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.