Reputation: 427
I'm looking at the implicit class example in the Scala Docs:
object Helpers {
implicit class IntWithTimes(x: Int) {
def times[A](f: => A): Unit = {
def loop(current: Int): Unit =
if(current > 0) {
f
loop(current - 1)
}
loop(x)
}
}
}
Can someone please explain this syntax and functionality?
times[A](f: => A)
Upvotes: 1
Views: 100
Reputation: 7152
def times[A](f: => A): Unit
is a function signature, where A
is a generic type parameter. It is unbound, thus it can be Any
'thing.
f: =>
is a by name parameter. That is the f is not evaluated when the function time
is called but only every time it is called within time
.
This is a good post about calling-by-name.
So in the example, if you have the implicit class in your scope you can do:
var count = 0
5 times { count += 1; println(count) }
and would get
1
2
3
4
5
as output.
Upvotes: 3
Reputation: 3294
times
is a polymorphic function which takes a single type parameter A
and a single value parameter f
. f
is function which has result of type A
. A function which takes another function as a parameter is called a higher-order function.
More info about these topics:
Upvotes: 1