Extending Scala collections

后端 未结 4 2181
执念已碎
执念已碎 2021-01-20 02:13

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         


        
4条回答
  •  醉酒成梦
    2021-01-20 02:20

    Are you sure you really need to extend Scala collection? To make the code above work you can do this:

    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
    

    In this case Tuple2Set is just the wrapper for any other Set implementations. This means you are not limited to HashSet anymore and your methods left and right will be available on any other implementations as well (like TreeSet).

    I think in most cases wrapping or composition+delegation works much better than inheritance (and causes less problems).

提交回复
热议问题