Home »
Scala
Anonymous functions in Scala
By IncludeHelp Last updated : October 20, 2024
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
(x: Int , y:Int) => x + y
(_: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