Higher-order Functions Example

Higher-order Functions
Here is another example of usage of higher-order functions:
class Decorator(left: String, right: String) {
  def layout[A](x: A) = left + x.toString() + right
}
object QuizfulTest extends App {
  def apply(f: Int => String, v: Int) = f(v)
  val decorator = new Decorator("[", "]")
  println(apply(decorator.layout, 2015))
}
Execution yields the output:
[2015]
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.
Read more: Scala documentation

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala snippets
Cosmo
Sign Up Now
or Subscribe for future quizzes