扩展Scala集合

Joh*_*rae 3 scala scala-collections

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

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

但是,当我尝试使用它与以下测试

  new Tuple2Set[String,String]() + (("x","y")) left
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误

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

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

ten*_*shi 7

你确定你真的需要扩展Scala集合吗?要使上面的代码工作,您可以这样做:

class Tuple2Set[T1,T2](set: Set[(T1, T2)]) {
  def left = set map ( _._1 )
  def right = set map ( _._2 )
}

implicit def toTuple2Set[T1, T2](set: Set[(T1, T2)]) = new Tuple2Set(set)

Set[(String, String)]() + (("x","y")) left
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Tuple2Set它只是任何其他Set实现的包装器.这意味着您不再局限于HashSet您的方法left,right也可以在任何其他实现上使用(如TreeSet).

我认为在大多数情况下,包装或组合+委派比继承更好(并且导致更少的问题).