High Order Functions

FILE : HighOrderFunctionsDemo

High order function is a function which receive or/and return other functions. And because in scala methods can be converted into functions then we can come across "high order methods"

//method
def highOrderMethod(f:Int=>Int): Int = f(1)

//function
val highOrderFunction : (Int=>Int) => Int = function => function(1)

The first place where we can come across high order functions in scala is collection API

val simpleAddFive:Int=>Int = i => i+5
List(1,2,3).map(simpleAddFive)

Return a Function

The same as we can pass a function to other function we can also return a function. This is very handy when we want to modify given function so it fits composition or if we want to inject initial data into function.

So we have an example of function which adds provided value to fixed initial value

def createAddToN(n:Int) : Int => Int = i => i+n
val addToThree=createAddToN(3)

Or we can return function with the same types as input but with some additional functionality - this is a functional implementation of a decorator pattern

title("Functional Decorator")
    def decorateWithLogging(original:Int=>Int) : Int=>Int = i => {
      println(s" [LOGGING] : received parameter : $i")
      original(i) //calling original
}

val decrement : Int=>Int = i => i-1

val decorated=decorateWithLogging(decrement)

Dependency injection

With high order function you can implement basic dependency injection which can create operations on injected context.

For example we can inject Dao and then return function which will operate on this DAO.

def injectDao(dao:UserDao) : Int=> Option[User] =  id => dao.findById(id)

val dao= new UserDao

val daoFunction: (Int) => Option[User] =injectDao(dao)

section("daoFunction(1) : "+daoFunction(1))

Exercises

FILE : HighOrderFunctionsExercises

Exercise1

results matching ""

    No results matching ""