Scala – Higher-Order Functions

Scala Higher-Order Functions

In this guide, we will discuss Scala Higher-Order Functions. Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function.

Try the following example program, apply() function takes another function f and a value v and applies function f to v.

Example

object Demo {
   def main(args: Array[String]) {
      println( apply( layout, 10) )
   }

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

   def layout[A](x: A) = "[" + x.toString() + "]"
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

[10]

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply