Execute Around Method Pattern
Java programmers are familiar with the synchronized block. When we enter a synchronized block, it obtains a monitor (lock) on the given object. That monitor is automatically released when we leave the block. The release happens even if the code within the block throws an unhandled exception. That kind of deterministic behavior is nice to have in a number of other situations far beyond that specific example.
Thanks to function values, you can implement those constructs in Scala quite easily. Let’s look at an example.
We have a class named Resource that needs to start some transaction automatically and end the transaction deterministically as soon as we’re done using the object. We can rely on the constructor to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access