我该如何解释像"fill [A](n:Int)(elem:⇒A)"这样的签名?

Lai*_*uan 1 methods scala

scaladocVector#fill样子:

def fill[A](n: Int)(elem: ? A): Vector[A]
n the number of elements contained in the collection.
elem the element computation
returns A collection that contains the results of n evaluations of elem.
Run Code Online (Sandbox Code Playgroud)

但这就是我调用它的方式:

Vector.fill[Boolean](5)(true)
Run Code Online (Sandbox Code Playgroud)

在哪里elem?这是什么意思?

4le*_*x1v 10

fillmethod(=> A)中的elems签名表示by-name参数.它与简单by-value参数(如n: Int您的示例中)的不同之处在于,在调用方法时不会计算,而是在方法体中引用它们时.

因此,方法填充意味着它获取结果Vector中的元素数量并使用类型A的元素填充它,by-name因为您可以填充向量,例如.使用对象,如果使用by-value参数,则生成的向量将包含相等的对象,但是使用by-value参数,它将在每个循环中粘贴新对象.

执行:

def fill[A](n: Int)(elem: => A): CC[A] = {
  val b = newBuilder[A]
  b.sizeHint(n)
  var i = 0
  while (i < n) {
    b += elem // compute elem and add to the collection
    i += 1
  }
  b.result
}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,每次在方法体中引用时,都会重新计算`by-name`参数. (2认同)