Is it possible to create a custom control structure with several code blocks, in the fashion of before { block1 } then { block2 } finally { block3 }? The question is about the sugar part only – I know the functionality can be easily achieved by passing the three blocks to a method, like doInSequence(block1, block2, block3).
A real life example. For my testing utilities I’d like to create a structure like this:
getTime(1000) {
// Stuff I want to repeat 1000 times.
} after { (n, t) =>
println("Average time: " + t / n)
}
EDIT:
Finally I came up with this solution:
object MyTimer {
def getTime(count: Int)(action : => Unit): MyTimer = {
val start = System.currentTimeMillis()
for(i <- 1 to count) { action }
val time = System.currentTimeMillis() - start
new MyTimer(count, time)
}
}
class MyTimer(val count: Int, val time: Long) {
def after(action: (Int, Long) => Unit) = {
action(count, time)
}
}
// Test
import MyTimer._
var i = 1
getTime(100) {
println(i)
i += 1
Thread.sleep(10)
} after { (n, t) =>
println("Average time: " + t.toDouble / n)
}
The output is:
1
2
3
...
99
100
Average time: 10.23
It is mostly based on the answer by Thomas Lockney, I just added the companion object to be able to import MyTimer._
Thank you all, guys.
For your given example, the key would be to have the return type of
getTimehave theaftermethod on it. Depending on the context, you could use a single class or trait which wraps up both methods. Here’s a very simplified example of how you might approach it: