Latest web development tutorials

Scala higher-order functions

Scala function Scala function

Higher-order functions (Higher-Order Function) is a function of the other functions of the operation.

Scala allowed higher-order functions, higher-order functions can be used as a parameter to another function, or as a function of the output.

The following example, apply () function uses another function f v and values ​​as parameters, and then call the function f parameter v:

object Test {
   def main(args: Array[String]) {

      println( apply( layout, 10) )

   }
   // 函数 f 和 值 v 作为参数,而函数 f 又调用了参数 v
   def apply(f: Int => String, v: Int) = f(v)

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

Implementation of the above code, the output is:

$ scalac Test.scala
$ scala Test
[10]

Scala function Scala function