Is it possible to save a block to a variable?

Hi, I’m new to Scala and trying to solidify my understanding of the syntax.

This code was presented in a book I’m reading (paraphrased):

case class WorkItem(time: Int, action: () => Unit)

def afterDelay(delay: Int)(block: => Unit) = {
    val item = WorkItem(delay, () => block)
}

I understand that afterDelay can be invoked like so:

afterDelay(0) {
    println("foo")
}

Is there a way to save println("foo") to a variable so that I can call afterDelay like afterDelay(0)(variable)? E.g.,

val printFoo = ???
afterDelay(0)(printFoo) 

Is something like the above possible?

Well, yes and no.

You can create a function of no argument and then pass the execution of such function like this:

val printFoo = () => {
  println("foo")
}
afterDelay(0)(printFoo()) 

Another option may be using lazy val but you have to be a little bit more careful with reuse.

lazy val printFoo = {
  println("foo")
}
afterDelay(0)(printFoo) 

Finally, not part of the stdlib but you could just use a “programs-as-values” library like cats-effect to achieve something similar like this:

val printFoo = IO.println("foo")
IO.sleep(5.seconds) >> printFoo
4 Likes

You could also use a method instead of a function value for your refactoring:

def printFoo = println("foo")
afterDelay(0)(printFoo)
4 Likes