How do I specify a newBuilder for a scala set?

北慕城南 提交于 2019-11-27 07:24:28

问题


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: _*))
}

This does not compile. Here is the error.

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?

In addition to Programming in Scala I've looked through various StackOverflow posts like this one, but remain mystified.


回答1:


Give this a shot:

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: _*))
}

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.



来源:https://stackoverflow.com/questions/16049978/how-do-i-specify-a-newbuilder-for-a-scala-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!