1

I am new to Scala and while was trying to understand implicits in Scala, I am getting hard time understand [A](f: => A) part. Can any one explain please?

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)
}

} }

This is being called as:

scala> import Helpers._
import Helpers._

scala> 5 times println("HI")
      HI
      HI
      HI
      HI
      HI

Reference : https://docs.scala-lang.org/overviews/core/implicit-classes.html

VictorGram
  • 2,521
  • 7
  • 48
  • 82
  • 1
    Possible duplicate of [Use of Scala by-name parameters](https://stackoverflow.com/questions/26663219/use-of-scala-by-name-parameters) – Dmytro Mitin May 03 '19 at 19:34
  • 1
    Also https://stackoverflow.com/questions/49707521/by-name-parameter-in-scala https://stackoverflow.com/questions/13337338/call-by-name-vs-call-by-value-in-scala-clarification-needed – Dmytro Mitin May 03 '19 at 19:34
  • 1
    https://docs.scala-lang.org/tour/by-name-parameters.html – Dmytro Mitin May 03 '19 at 19:35
  • 1
    https://alvinalexander.com/scala/fp-book/how-to-use-by-name-parameters-scala-functions https://alvinalexander.com/source-code/scala/simple-scala-call-name-example https://tpolecat.github.io/2014/06/26/call-by-name.html – Dmytro Mitin May 03 '19 at 19:36

1 Answers1

4

Let's disect this method declaration:

def times[A](f: => A): Unit
  • def: keyword used to define a method
  • times: method name
  • [A]: a type parameter named A. This means that this method takes a type parameter which can be passed either explicitly (e.g. by calling times[Int](...)) or implicitly (calling times(...) and letting compiler infer the type) when the method is called. See https://docs.scala-lang.org/tour/polymorphic-methods.html for more details
  • (f: => A): these are the method's "value parameters", in this case there's exactly one such parameter, named f, of type A (which is the type parameter we've declared!). The => signifies that this parameter is a call-by-name parameter, see https://docs.scala-lang.org/tour/by-name-parameters.html
  • : Unit: this is the method's return type - defined to be Unit, practically meaning this method doesn't return any value
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85