6

のように、複数のコードブロックを使用してカスタム制御構造を作成することは可能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._

みんなありがとう。

4

4 に答える 4

13

一般原則。もちろん、fにパラメータを取得させることもできます。(この例では、メソッドの名前には意味がないことに注意してください。)

scala> class Foo {
     | def before(f: => Unit) = { f; this }
     | def then(f: => Unit) = { f; this }
     | def after(f: => Unit) = { f; this }
     | }
defined class Foo

scala> object Foo { def apply() = new Foo }
defined module Foo

scala> Foo() before { println("before...") } then {
     | println("then...") } after {
     | println("after...") }
before...
then...
after...
res12: Foo = Foo@1f16e6e
于 2011-01-01T10:06:26.303 に答える
8

これらのブロックを特定の順序で表示する場合は、Knut Arne Vedaa の回答へのこの変更が機能します。

class Foo1 {
  def before(f: => Unit) = { f; new Foo2 }
}

class Foo2 {
  def then(f: => Unit) = { f; new Foo3 }
}

...
于 2011-01-01T11:01:19.607 に答える
3

あなたの与えられた例では、重要なのは、returnタイプにgetTimeメソッドafterがあることです。コンテキストに応じて、両方のメソッドをラップする単一のクラスまたはトレイトを使用できます。これは、アプローチ方法の非常に単純化された例です。

class Example() {
  def getTime(x: Int)(f : => Unit): Example = {
    for(i <- 0 to x) {
      // do some stuff
      f
      // do some more stuff
    }
    // calculate your average
    this
  }
  def after(f: (Int, Double) => Unit) = {
    // do more stuff
  }
}
于 2011-01-01T09:26:33.713 に答える
1

「分割」メソッドを持つことはできませんが、エミュレートすることはできます。

class Finally(b: => Unit, t: => Unit) {
    def `finally`(f: => Unit) = {
        b
        try { t } finally { f }
    }
}

class Then(b: => Unit) {
    def `then`(t: => Unit): Finally = new Finally(b, t)
}

def before(b: => Unit): Then = new Then(b)

scala> before { println("Before") } `then` { 2 / 0 } `finally` { println("finally") }
Before
finally
[line4.apply$mcV$sp] (<console>:9)
(access lastException for the full trace)
scala>
于 2011-01-02T13:30:51.753 に答える