[英]scala call-by-name - declaring parameters that aren't used
按名稱調用的好處之一是,在以下示例中不會運行昂貴的Operation():
按值致電:
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() )
我的問題是,為什么不使用它時為什么要聲明一個函數參數?
您的示例有些人為,請考慮以下代碼
def test( x: Boolean, y: => Int ): Int = if(x) y else 0
// expensionOperation is not evaluated
test( false, expensiveOperation() )
當第一個參數為false時,您將節省大量時間,無需評估昂貴的操作。
這只是一個虛構的例子,用來說明按名稱調用的想法,即,傳入的參數如果不被調用就不會被求值。
也許更好的例子如下:
trait Option[+T] {
def getOrElse[B >: A](default: => B): B
}
如果Option
為Some
,則返回包裝的值,並且從不評估default
值。 如果為None
且僅當為None
將default
評估(並因此返回)。
使用日志記錄是一個更好的示例:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.