1

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) 

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.