Is it possible to create a custom control structure with several blocks of code, in the order before { block1 } then { block2 } finally { block3 } ? The only question is sugar - I know that functionality can be easily achieved by passing three blocks to a method, for example doInSequence(block1, block2, block3) .
Real life example. For my testing utilities, I would 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) } }
Output:
1 2 3 ... 99 100 Average time: 10.23
Basically, based on Thomas Lockney's answer, I just added a companion object to be able to import MyTimer._
Thanks guys.
scala control-structure
Vilius normantas
source share