简体   繁体   English

Scala按名称调用-声明未使用的参数

[英]scala call-by-name - declaring parameters that aren't used

One of the benefits of call-by-name is that expensiveOperation() will not get run in the following examples: 按名称调用的好处之一是,在以下示例中不会运行昂贵的Operation():

Call-by-value: 按值致电:

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

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

Call-by-name: 姓名呼叫:

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

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

My question though is why would you declare a function parameter (y in my case) when you aren't going to use it? 我的问题是,为什么不使用它时为什么要声明一个函数参数?

Your example is a bit contrived, consider this code 您的示例有些人为,请考虑以下代码

def test( x: Boolean, y: => Int ): Int = if(x) y else 0

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

When the first parameter is false you are saving a lot of time not evaluating expensive operation. 当第一个参数为false时,您将节省大量时间,无需评估昂贵的操作。

It is just a contrived example to illustrate the idea of call-by-name, namely that the argument passed in is never evaluated if never called. 这只是一个虚构的例子,用来说明按名称调用的想法,即,传入的参数如果不被调用就不会被求值。

Perhaps a better example would be the following: 也许更好的例子如下:

trait Option[+T] {
    def getOrElse[B >: A](default: => B): B
}

If the Option is Some , then the wrapped value is returned and default is never evaluated. 如果OptionSome ,则返回包装的值,并且从不评估default值。 If it is None and only when it is None will default be evaluated (and consequently returned). 如果为None且仅当为Nonedefault评估(并因此返回)。

Using logging is a much better example: 使用日志记录是一个更好的示例:

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

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

While in the case of call-by-name: 如果是按姓名致电:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM