A Scala method to run any block of code slowly

The book, Advanced Scala with Cats, has a nice little function you can use to run a block of code “slowly”:

def slowly[A](body: => A) = try body finally Thread.sleep(100)

I’d never seen a try/finally block written like that, so it was something new for the brain.

In the book they run a factorial method slowly, like this:

slowly(factorial(n - 1).map(_ * n))

FWIW, you can modify slowly to pass in the length of time to sleep, like this:

def slowly[A](body: => A, sleepTime: Long) = try body finally Thread.sleep(sleepTime)
Scala: How to declare a variable (var) before using it in try/catch/finally alvin June 7, 2015 - 4:04pm

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.17, “How to declare a variable (var) before using it in try/catch/finally.”


You want to use an object in a try block, and need to access it in the finally portion of the block, such as when you need to call a close method on an object.

A Scala Either, Left, and Right example (like Option, Some, and None) alvin October 4, 2012 - 4:38pm
Scala: A discussion of the Option/Some/None pattern, and how to use Either/Left/Right instead, when you need to know why something failed.
The Scala try, catch, finally syntax (multiple exceptions, wildcard operator) alvin November 9, 2011 - 11:49am

Scala FAQ: Can you share some examples of the Scala try/catch/finally syntax? Also, can you show how to catch multiple exceptions, and just one exception with the Scala wildcard operator (_)?

The general Scala try/catch/finally syntax looks like this:

A Java JDBC exception example showing try, catch, and finally

Java/JDBC try/catch/finally exception FAQ: Can you show me a decent example of how to catch a JDBC exception in a try/catch/finally block?

Beauty is in the eye of the beholder, but here's a JDBC example showing some Java code that uses a try/catch/finally block with a Java JDBC query: