MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Higher Order Function

Examples

Using methods as function values


The Scala compiler will automatically convert methods into function values for the purpose of passing them into higher-order functions.

object MyObject {
 def mapMethod(input: Int): String = {
 int.toString
 }
}
Seq(1, 2, 3).map(MyObject.mapMethod) // Seq("1", "2", "3")

In the example above, MyObject.mapMethod is not a function call, but instead is passed to map as a value. Indeed, map requires a function value passed to it, as can be seen in it's signature. The signature for the map of a List[A] (a list of objects of type A) is:

def map[B](f: (A) ⇒ B): List[B]

The f: (A) => B part indicates that the parameter to this method call is some function that takes an object of type A and returns an object of type B. A and B are arbitrarily defined. Returning to the first example, we can see that mapMethod takes an Int (which corresponds to A) and returns a String (which corresponds to B). Thus mapMethod is a valid function value to pass to map. We could rewrite the same code like this:

Seq(1, 2, 3).map(x:Int => int.toString)

This inlines the function value, which may add clarity for simple functions.

High Order Functions(Function as Parameter)


A higher-order function, as opposed to a first-order function, can have one of three forms:

• One or more of its parameters is a function, and it returns some value.

• It returns a function, but none of its parameters is a function.

•Both of the above: One or more of its parameters is a function, and it returns a function.


object HOF {
 def main(args: Array[String]) {
 val list =
List(("Srini","E"),("Subash","R"),("Ranjith","RK"),("Vicky","s"),("Sudhar","s"))
 //HOF
 val fullNameList= list.map(n => getFullName(n._1, n._2))
 }
 def getFullName(firstName: String, lastName: String): String = firstName + "." +
lastName
 }


Here the map function takes a getFullName(n._1,n._2) function as a parameter. This is called HOF (Higher order function).

Arguments lazy evaluation


Scala supports lazy evaluation for function arguments using notation: def func(arg: => String). Such function argument might take regular String object or a higher order function with String return type. In second case, function argument would be evaluated on value access.

Please see the example:

def calculateData: String = {
 print("Calculating expensive data! ")
 "some expensive data"
}
def dumbMediator(preconditions: Boolean, data: String): Option[String] = {
 print("Applying mediator")
 preconditions match {
 case true => Some(data)
 case false => None
 }
}
def smartMediator(preconditions: Boolean, data: => String): Option[String] = {
 print("Applying mediator")
 preconditions match {
 case true => Some(data)
 case false => None
 }
}
smartMediator(preconditions = false, calculateData)
dumbMediator(preconditions = false, calculateData)


Conclusion

In this page (written and validated by ) you learned about Scala Higher Order Function . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala If Expressions.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.