0

I understand that a "call by name" argument is defined as foo(arg: => T) but, what does this mean?

def foo(block: => T) = {
  List(1, 2, 3).map(_ => ()=>block)
}

Specially I don't understant the ()=> part.

Wouldn't it be enough to write map(_ => argByName) ?

hanbzu
  • 880
  • 1
  • 8
  • 14

1 Answers1

3

It's a function literal

scala> val f = () => 1
f: () => Int = <function0>

scala> f()
res0: Int = 1

map(_ => block) would evaluate block immediately; by keeping it as a function we keep it lazy, which matters if we pass a block with side effects.

def foo2[T](block: => T) = List(1, 2, 3).map(_ => block)

scala> foo2(println("Hello"))
Hello
Hello
Hello
res1: List[Unit] = List((), (), ())

scala> foo(println("Hello"))
res2: List[() => Unit] = List(<function0>, <function0>, <function0>)

scala> res2.map(_())
Hello
Hello
Hello
res3: List[Unit] = List((), (), ())
lmm
  • 17,386
  • 3
  • 26
  • 37