Scala - 类型 T 或 => 的参数吨 [英] Scala - parameter of type T or => T

查看:55
本文介绍了Scala - 类型 T 或 => 的参数吨的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下有区别吗

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

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

这两个定义都接受sss"作为参数.

both these definitions accept "sss" as parameter.

推荐答案

一个参数 String 是一个 by-value 参数,=>String 是一个 by-name 参数.在第一种情况下,字符串被传入,在第二种情况下,一个所谓的 thunk 在使用时评估一个String.

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)

这篇关于Scala - 类型 T 或 => 的参数吨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆