Scala higher-order functions

For me personally, very difficult to thing recursively. So I’ll put some examples for me down here.

First – higher-order function is a function takes function as an argument or returns result as a function.

Lets create a high-order function in scala:

scala> def highF(f: Int => Int, a: Int) = f(a)
highF: (f: Int => Int, a: Int)Int

As we can see it does not do anything usable. Just takes f(Int) and returns Int.

Lets create two first class functions:

scala> def first1(a: Int) : Int = { a.+(a) }
first1: (a: Int)Int

scala> def first2(a: Int) : Int = { a.-(a) }
first2: (a: Int)Int

This functions are already easier to explain. First one takes Int and just does Int + Int. In example a => a + a.

Second one just subtracts a => a – a.

Now comes interesting part – how we use higher-order function.

scala> highF(first1, 2)
res23: Int = 4

scala> highF(first2, 2)
res24: Int = 0

And there is more. We can use anonymous function as an argument:

scala> highF(a => a.+(10), 2)
res25: Int = 12

Posted in IT