Higher-Order functions are functions that take other functions as parameters, or whose result is a function.
class Decorator(left: String, right: String) {
def layout[A](x: A) = left + x.toString() + right
}
object FunTest extends Application {
def apply(f: Int => String, v: Int) = f(v)
val decorator = new Decorator("[", "]")
println(apply(decorator.layout, 7))
}
The type Int => String is the type of functions that take arguments of type Int and return results of type String.
Here is a function
apply
which takes another function f
and a value v
and applies function f
to v
:Anonymous Functions:
An anonymous function is an expression that evaluates to a function; the function is defined without
giving it a name.
(x: Int) => x * x
The part before the arrow ‘=>’ are the parameters of the function, whereas the part
following the ‘=>’ is its body. The Scala compiler can deduce the parameter type(s) fromthe context of the anonymous function in which case they can be omitted.
Reference:
http://www.scala-lang.org/old/node/134.html
No comments:
Post a Comment