如何为scala集指定一个newBuilder? [英] How do I specify a newBuilder for a scala set?

查看:110
本文介绍了如何为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.

这篇关于如何为scala集指定一个newBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆