如何为scala集指定一个newBuilder?
我正在尝试在Scala中扩展一组整数。根据早期答案,我决定使用SetProxy对象。我现在正在尝试实施 Scala编程第二版第25章中所述的 newBuilder
机制,并且遇到了麻烦。具体来说,我无法弄清楚要为 SetBuilder
对象指定什么参数。这是我尝试过的。
I am trying to extend a set of integers in Scala. Based on an earlier answer I have decided to use a SetProxy object. I am now trying to implement the newBuilder
mechanism as described in chapter 25 of the second edition of Programming in Scala and am having trouble. Specifically I cannot figure out what parameter to specify to the SetBuilder
object. Here is what I have tried.
package example
import scala.collection.immutable.{HashSet, SetProxy}
import scala.collection.mutable
case class CustomSet(override val self: Set[Int]) extends SetProxy[Int] {
override def newBuilder[Int, CustomSet] =
new mutable.SetBuilder[Int, CustomSet](CustomSet())
}
object CustomSet {
def apply(values: Int*): CustomSet = CustomSet(HashSet(values.toSeq: _*))
}
不编译。这是错误。
scala: type mismatch;
found : example.CustomSet
required: CustomSet
override def newBuilder[Int, CustomSet] = new mutable.SetBuilder[Int, CustomSet](CustomSet())
^
这对我来说是个谜。我已经尝试过对有问题的值进行各种变体,但是没有一个起作用。我该如何进行编译?
This is mystifying to me. I've tried various variations on the problematic value, but none of them work. How do I make this compile?
除了在Scala中编程之外,我还浏览了各种StackOverflow帖子,例如这一个,但保持神秘感。
In addition to Programming in Scala I've looked through various StackOverflow posts like this one, but remain mystified.
试一下:
case class CustomSet(override val self: Set[Int]) extends SetProxy[Int] {
override def newBuilder = new mutable.SetBuilder[Int, Set[Int]](CustomSet())
}
object CustomSet {
def apply(values: Int*): CustomSet = CustomSet(HashSet(values.toSeq: _*))
}
在创建 SetBuilder
时,未指定 CustomSet
作为第二种类型的参数满足该参数绑定的类型。将其切换为 Set [Int]
符合该条件,并允许您仍将 CustomSet
作为构造函数arg传递。希望这会有所帮助。
When creating the SetBuilder
, specifying CustomSet
as the second type param did not satisfy the type bound for that param. Switching it to Set[Int]
meets that criteria and allows you to still pass in your CustomSet
as the constructor arg. Hope this helps.