Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

builder - How do I specify a newBuilder for a scala set?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...