扩展 Scala 集合 [英] Extending Scala collections

查看:48
本文介绍了扩展 Scala 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想派生一个 Scala 内置集合的版本,它扩展了特定泛型类型的功能,例如,

I would like to derive a version of a Scala built-in collection that expands on the functionality for a particular generic type e.g.,

import scala.collection.immutable._
class Tuple2Set[T1,T2] extends HashSet[Tuple2[T1,T2]] {
 def left = map ( _._1 )
 def right = map ( _._2 )
}

但是当我尝试将其用于以下测试时

However when I try to use it with the following test

  new Tuple2Set[String,String]() + (("x","y")) left

我收到以下编译错误

error: value left is not a member of scala.collection.immutable.HashSet[(String, String)]

如何更改课程以使其有效?

How can I change the class so that this works?

推荐答案

正如Kevin Wright所说,+操作会返回HashSet.类型类CanBuildFrom 用于在map 等操作期间构建新集合.因此,如果您希望 + 返回 Tuple2Set 而不是 HashSet,您应该实现 CanBuildFrom 并使其在伴随中隐式可用像这样的对象:

As Kevin Wright said, + operation will return back HashSet. Type class CanBuildFrom is used to build new collections during operations like map. So if you want + to return Tuple2Set instead of HashSet you should implement CanBuildFrom and make it implicitly available in companion object like this:

object Tuple2Set {
    implicit def canBuildFrom[T1, T2] = 
        new CanBuildFrom[Tuple2Set[T1, T2], (T1, T2), Tuple2Set[T1, T2]] {...}
}

这篇关于扩展 Scala 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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