Scala Higher Order FunctionsHigher order function is a function that either takes a function as argument or returns a function. In other words we can say a function which works with function is called higher order function. Higher order function allows you to create function composition, lambda function or anonymous function etc. Let's see an example. Scala Example: Passing a Function as Parameter in a FunctionOutput: 60 Scala Example: Function CompositionIn scala, functions can be composed from other functions. It is a process of composing in which a function represents the application of two composed functions. Let's see an example. Output: 24 Scala Anonymous (lambda) FunctionAnonymous function is a function that has no name but works as a function. It is good to create an anonymous function when you don't want to reuse it latter. You can create anonymous function either by using => (rocket) or _ (underscore) wild card in scala. Let's see an example. Scala Anonymous function ExampleOutput: 20 20 Scala Multiline ExpressionExpressions those are written in multiple lines are called multiline expression. In scala, be carefull while using multiline expressions. The following program explains about if we break an expression into multiline, the scala compiler throw a warning message. Scala Multiline Expression ExampleThe above program does not evaluate complete expression and just return b here. So, be careful while using multiline expressions. Output: MainObject.scala:3: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses a ^ one warning found 10 You can apply following ways to avoid above problem. Scala Example Multiline ExpressionOutput: 20 20 Scala Function CurryingIn scala, method may have multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments. In other words it is a technique of transforming a function that takes multiple arguments into a function that takes a single argument. Scala Function Currying ExampleOutput: 20 Scala Nested FunctionsScala is a first class function language which means it allows you to passing function, returning function, composing function, nested function etc. An example below explain about how to define and call nested functions. Scala Nested Functions ExampleOutput: 30 Scala Function with Variable Length ParametersIn scala, you can define function of variable length parameters. It allows you to pass any number of arguments at the time of calling the function. Let's see an example. Scala Example: Function with Variable Length ParametersOutput: 45 Next TopicScala Object and Class |