争论懒惰的评价

Scala 支持使用表示法对函数参数进行延迟评估:def func(arg: => String)。这样的函数参数可以采用常规 String 对象或 String 返回类型的高阶函数。在第二种情况下,将对值访问评估函数参数。

请看示例:

def calculateData: String = {
  print("Calculating expensive data! ")
  "some expensive data"
}

def dumbMediator(preconditions: Boolean, data: String): Option[String] = {
  print("Applying mediator")
  preconditions match {
    case true => Some(data)
    case false => None
  }
}

def smartMediator(preconditions: Boolean, data: => String): Option[String] = {
  print("Applying mediator")
  preconditions match {
    case true => Some(data)
    case false => None
  }
}

smartMediator(preconditions = false, calculateData)

dumbMediator(preconditions = false, calculateData)

smartMediator 调用将返回无值并打印消息 Applying mediator

dumbMediator 调用将返回无值并打印消息 Calculating expensive data! Applying mediator

当你想要优化昂贵的参数计算开销时,延迟评估可能非常有用。