top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is an Higher-Order Function (HOF) in Scala?

+2 votes
240 views
What is an Higher-Order Function (HOF) in Scala?
posted Jul 20, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Here is a function apply which takes another function f and a value v and applies function f to v:

def apply(f: Int => String, v: Int) = f(v)

Note: methods are automatically coerced to functions if the context requires this.

Here is another example:

class Decorator(left: String, right: String) {
  def layout[A](x: A) = left + x.toString() + right
}
object FunTest extends App {
  def apply(f: Int => String, v: Int) = f(v)
  val decorator = new Decorator("[", "]")
  println(apply(decorator.layout, 7))
}

Execution yields the output:

[7]

In this example, the method decorator.layout is coerced automatically to a value of type Int => String as required by method apply. Please note that method decorator.layout is a polymorphic method (i.e. it abstracts over some of its signature types) and the Scala compiler has to instantiate its method type first appropriately.

answer Sep 2, 2016 by Shyam
...