Scala Anonymous Functions | Tutorial
Tutorial --
Scala Tutorial
Scala TutorialScala IntroductionScala Installation and Environment ConfigurationScala Basic SyntaxScala Data TypesScala Literals Scala Escape Characters Scala VariablesScala Access ModifiersScala OperatorsScala IF...ELSE StatementsScala LoopsScala Methods and FunctionsScala ClosuresScala StringsScala ArraysScala CollectionScala IteratorScala Classes and ObjectsScala TraitScala Pattern MatchingScala Regular ExpressionsScala Exception HandlingScala ExtractorScala File I/O
Scala Loops
Scala Closures
Scala Anonymous Functions
Scala Functions
The syntax for defining anonymous functions in Scala is very simple: the left side of the arrow is the parameter list, and the right side is the function body.
Using anonymous functions makes our code more concise.
The following expression defines an anonymous function that takes an Int type input parameter:
var inc = (x:Int) => x+1
The anonymous function defined above is actually a shorthand for the following:
def add2 = new Function1[Int,Int]{ def apply(x:Int):Int = x+1; }
The
inc in the above example can now be used as a function, as follows:
var x = inc(7)-1
Similarly, we can define multiple parameters in an anonymous function:
var mul