Reputation: 20856
IM trying to understand the below high order functions in Scala but need some clarifications on the parameters of the functions.
Questions:-
Int => String
in the apply
function mean?
v: Int
indicates that the parameter v is of type Int
.What does the [A](x: A)
mean in layout
function?
object Demo {
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() + "]"
}
Upvotes: 1
Views: 155
Reputation: 15413
The syntax of Int => String
means passing a function that accepts Int
and returns String
.
Here is a useful example for passing function:
case class Person(name: String, lastName: String)
val person = Person("Johnny", "Cage")
def updateName(name: String) = {
updatePerson(_.copy(name = name))
}
def updateLastName(lastName: String) {
updatePerson(_.copy(lastName = lastName))
}
private def updatePerson(transformer: Person => Person): Unit = {
transformer(person)
}
Note how each update
function passes the copy constructor.
Upvotes: 0
Reputation: 7591
f: Int => String
means that f
is a function with one argument of type Int
and with a return type String
def layout[A](x: A)
means that parameter x
is of type A
, which can be of any type. Here are a couple of examples on how to invoke layout:
layout[String]("abc") //returns "[abc]"
layout[Int](123) //returns "[123]"
When main
runs it invokes apply
with the layout
function and the argument 10. This will output "[10]"
Upvotes: 10