2

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.

Community
  • 1
  • 1
W.P. McNeill
  • 16,336
  • 12
  • 75
  • 111

1 Answers1

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.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • Proxy classes look like the ideal way to (effectively) subclass from traits with implementation classes that don't want to be subclassed. However, as of Scala 2.11.0, they have been [deprecated](http://stackoverflow.com/questions/24312563). – Ben Kovitz Jun 19 '14 at 18:10