Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Higher-Order Functions

Scala Higher-Order Functions

Scala functions Scala Functions

A higher-order function is a function that operates on other functions.

Scala allows higher-order functions; they can take other functions as parameters or return functions as results.

In the following example, the apply() function takes another function f and a value v as parameters, and f in turn calls the parameter v:



object Test {

   def main(args: Array[String]) {



      println( apply( layout, 10) )



   }

   // Function f and value v as parameters, and function f calls parameter v

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



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

   

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

[10]

Scala functions Scala Functions