Cra*_*ker 3 scala map variadic-functions
我刚开始学习Scala.在浏览Scaladocs时,我看到了这个方法定义mutable.Map:
def -=(elem1: A, elem2: A, elems: A*): Map.this.type
Removes two or more elements from this shrinkable collection.
elem1 the first element to remove.
elem2 the second element to remove.
elems the remaining elements to remove.
returns the shrinkable collection itself
Run Code Online (Sandbox Code Playgroud)
为什么你需要定义elem1和elem2明确的,如果你只是去定义elems一个*呢?
请注意,已经有一个带有单个参数的单独重载方法:
abstract def -=(key: A): Map.this.type
Run Code Online (Sandbox Code Playgroud)
所以两个更多的参数约束是避免模糊调用.使用单个参数的单独方法的原因可能是效率.请注意,调用变量参数方法涉及在后台创建一个数组,如果只有一个要删除的元素,则会浪费这些数组.
由于该方法的单参数版本是抽象的而多参数版本是具体的,如果后者的实现实际上称之为(功能等同于)循环,我不会感到惊讶.(更新:快速代码检查验证了我的猜测,虽然呼叫是间接通过--=.)