爭論懶惰的評價

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

當你想要優化昂貴的引數計算開銷時,延遲評估可能非常有用。