Scala higher order function


Release date:2023-11-17 Update date:2023-11-17 Editor:admin View counts:140

Label:

Scala higher order function

Higher-Order Function are functions that operate onother functions.

Higher-order functions are allowed in Scala, and higher-order functions can use other functions as parameters or functions as output.

In the following example the apply() function takes another function f and the value v as arguments, and function f calls the parameter v:

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

      println( apply( layout, 10) )

   }
   // Function f and value v are used as parameters, while function f calls parameter v
   def apply(f: Int => String, v: Int) = f(v)

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

}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
[10]

Powered by TorCMS (https://github.com/bukun/TorCMS).