使用新属性扩展 scala 集合
如果我有一个带有附加属性的新集合,例如:
class NewColl(var name: String, var values: Vector[Int])
extends IndexedSeq[Int] with IndexedSeqLike[Int, NewColl] {...}
如何定义 canBuildFrom
和 newBuilder
(参见 此处)这样,如果:
var v1 = NewColl("foo",Vector(1,2,3))
var v2 = v1 filter(_ > 1)
var v3 = v1 map(_ + 1)
则 v2.name=="foo"
和v3.name==“foo”
?
If I have a new collection with an additional attribute, e.g. :
class NewColl(var name: String, var values: Vector[Int])
extends IndexedSeq[Int] with IndexedSeqLike[Int, NewColl] {...}
how do I define canBuildFrom
and newBuilder
(cf. here) such that if:
var v1 = NewColl("foo",Vector(1,2,3))
var v2 = v1 filter(_ > 1)
var v3 = v1 map(_ + 1)
then v2.name=="foo"
and v3.name=="foo"
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
请注意,我已将您的
var
更改为val
,以便与不可变集合保持一致。已混合使用SeqForwarder
以避免实现将全部转发到values
上的同一方法的方法列表。newBuilder
已在伴生对象上实现,需要一个String
参数。请注意,有时,集合可以自由地在
CanBuildFrom
上调用apply()
,而无需指定原始集合。在这种情况下,您要么必须提供默认名称,要么(像这里一样)抛出异常(仅当您不设计库并控制新集合的使用时才允许)。另请参阅该问题。
Try this:
Note that I've changed your
var
s intoval
s here to be consistent with an immutable collection.SeqForwarder
has been mixed in to avoid implementing a list of methods that would all forward to the same method onvalues
.newBuilder
has been implemented on the companion object and needs aString
parameter.Note that sometimes, collections are free to call
apply()
on theCanBuildFrom
without specifying the originating collection. In that case, you either have to provide a default name, or (like here) throw an exception (permissible only if you're not designing a library and control the use of your new collection).See also that question.