Subject not found.
1.

Explain ‘scala Higher Order’ Functions?

Answer»

Scala allows the definition of higher order functions. These are functions that take other functions as parameters, or whose result is a FUNCTION. In the following example, apply () function takes another function ‘f’ and a value ‘v’ and applies function to v.

Example:

object Test {
 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() + "]"

When the above code is compiled and EXECUTED, it produces following result.

C:/>scalac Test.scala
C:/>scala Test
[10]
C:/>

Scala allows the definition of higher order functions. These are functions that take other functions as parameters, or whose result is a function. In the following example, apply () function takes another function ‘f’ and a value ‘v’ and applies function to v.

Example:

object Test {
 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() + "]"

When the above code is compiled and executed, it produces following result.

C:/>scalac Test.scala
C:/>scala Test
[10]
C:/>



Discussion

No Comment Found