Scala - parameter of type T or => T

拜拜、爱过 提交于 2021-02-07 08:16:20

问题


Is there any difference between the following

def foo(s: String) = { ... }

and

def foo(s: => String) { ... }

both these definitions accept "sss" as parameter.


回答1:


An argument String is a by-value parameter, => String is a by-name parameter. In the first case, the string is passed in, in the second a so-called thunk which evaluates to a String whenever it is used.

def stringGen: String = util.Random.nextInt().toString

def byValue(s: String) =
  println("We have a '" + s + "' and a '" + s + "'")

def byName(s: => String) =
  println("We have a '" + s + "' and a '" + s + "'")

byValue(stringGen)  // constant value
byName (stringGen)  // evaluated twice

Often a by-name parameter is not used to evaluate it several times, but to lazily evaluate it once.

def logMessage = {
  println("Calculating log message...")
  new java.util.Date().toString
}

def log(enabled: Boolean, message: => String): Unit = {
  lazy val fullMessage = "LOG: " + message
  println("Test")
  if (enabled) println(fullMessage)
}

log(false, logMessage)
log(true , logMessage)



回答2:


In many cases they are the same, but

The => passes by name

The first passes by value



来源:https://stackoverflow.com/questions/11992134/scala-parameter-of-type-t-or-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!