のように、複数のコードブロックを使用してカスタム制御構造を作成することは可能before { block1 } then { block2 } finally { block3 }
ですか?問題は砂糖の部分だけです-のようなメソッドに3つのブロックを渡すことで、機能を簡単に実現できることを私は知っていますdoInSequence(block1, block2, block3)
。
実際の例。私のテストユーティリティでは、次のような構造を作成したいと思います。
getTime(1000) {
// Stuff I want to repeat 1000 times.
} after { (n, t) =>
println("Average time: " + t / n)
}
編集:
最後に私はこの解決策を思いついた:
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)
}
出力は次のとおりです。
1
2
3
...
99
100
Average time: 10.23
これは主にトーマス・ロックニーの回答に基づいています。コンパニオンオブジェクトを追加しただけです。import MyTimer._
みんなありがとう。