1

名前による呼び出しの利点の 1 つは、次の例では、expectedOperation() が実行されないことです。

値による呼び出し:

def test( x: Int, y: Int ): Int = x * x

// expensiveOperation is evaluated and the result passed to test()
test( 4, expensiveOperation() )  

名前による呼び出し:

def test( x: Int, y: => Int ): Int = x * x

// expensionOperation is not evaluated
test( 4, expensiveOperation() ) 

私の質問は、関数パラメーター (私の場合は y) を使用しないのに、なぜ宣言するのでしょうか?

4

3 に答える 3

2

ロギングの使用は、より良い例です:

def debug(msg: String) = if (logging.enabled) println(msg)

debug(slowStatistics()) // slowStatistics will always be evaluated

一方、名前による呼び出しの場合:

def debug(msg: => String) = if (logging.enabled) println(msg)

debug(slowStatistics()) // slowStatistics will be evaluated only if logging.enabled
于 2013-08-02T11:47:14.660 に答える