gpt4 book ai didi

scala - 使用重复参数的成本

转载 作者:行者123 更新时间:2023-12-04 18:16:31 24 4
gpt4 key购买 nike

我考虑重构一些当前采用具体类的ListSet类型参数(List[Foo])的方法签名,以使用重复的参数:Foo*

Update: Following reasoning is flawed, move along...
This would allow me to use the same method name and overload it based on the parameter type. This was not possible using List or Set, because List[Foo] and List[Bar] have same type after erasure: List[Object].



在我的情况下,重构的方法可以使用由重复参数产生的 scala.Seq[Foo]正常工作。我将不得不更改所有调用,并向所有集合参数添加一个序列参数类型注释: baz.doStuffWith(foos:_*)

假设从collection参数切换到重复参数在语义上是等效的,那么此更改是否会对性能产生影响,我应该注意这些影响?

Scala 2.7._和2.8的答案是否相同?

最佳答案

当Scala调用Scala varargs方法时,该方法将接收扩展了Seq的对象。当使用: _*进行调用时,该对象将按原样*传递,而不进行复制。以下是示例:

scala> object T {
| class X(val self: List[Int]) extends SeqProxy[Int] {
| private val serial = X.newSerial
| override def toString = serial.toString+":"+super.toString
| }
| object X {
| def apply(l: List[Int]) = new X(l)
| private var serial = 0
| def newSerial = {
| serial += 1
| serial
| }
| }
| }
defined module T

scala> new T.X(List(1,2,3))
res0: T.X = 1:List(1, 2, 3)

scala> new T.X(List(1,2,3))
res1: T.X = 2:List(1, 2, 3)

scala> def f(xs: Int*) = xs.toString
f: (Int*)String

scala> f(res0: _*)
res3: String = 1:List(1, 2, 3)

scala> f(res1: _*)
res4: String = 2:List(1, 2, 3)

scala> def f(xs: Int*): Seq[Int] = xs
f: (Int*)Seq[Int]

scala> def f(xs: Int*) = xs match {
| case ys: List[_] => println("List")
| case _ => println("Something else")
| }
f: (Int*)Unit

scala> f(List(1,2,3): _*)
List

scala> f(res0: _*)
Something else

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> def f(xs: Int*) = xs match {
| case ys: List[_] => println("List")
| case zs: ArrayBuffer[_] => zs.asInstanceOf[ArrayBuffer[Int]] += 4; println("Array Buffer")
| case _ => println("Something else")
| }
f: (Int*)Unit

scala> val ab = new ArrayBuffer[Int]()
ab: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> ab + 1
res11: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1)

scala> ab + 2
res12: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2)

scala> ab + 3
res13: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)

scala> f(ab: _*)
Array Buffer

scala> ab
res15: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)

注意
  • Array作为WrappedArray传递。但是,不会复制涉及的元素,并且对WrappedArray的更改将反射(reflect)在Array中。
  • 关于scala - 使用重复参数的成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451845/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com