Extend Scala Set with concrete type

后端 未结 2 580
情书的邮戳
情书的邮戳 2021-01-14 17:26

Really struggling to figure out extending the immutable Set with a class that will represent a Set of concrete type. I\'m doing this to try and create a nice DSL.

I

2条回答
  •  不思量自难忘°
    2021-01-14 18:05

    Adapting from this Daily Scala post as well as the source to BitSet, which is a wonderful example here because it is not a parameterized collection, and is rather short and simple.

    import scala.collection.SetLike
    import scala.collection.generic.{GenericSetTemplate, GenericCompanion, CanBuildFrom}
    import scala.collection.mutable.{Builder, SetBuilder}
    
    class ThingSet(seq : Thing*) extends Set[Thing] 
                                 with SetLike[Thing, ThingSet]
                                 with Serializable {
        override def empty: ThingSet = new ThingSet()
        def + (elem: Thing) : ThingSet = if (seq contains elem) this 
            else new ThingSet(elem +: seq: _*)
        def - (elem: Thing) : ThingSet = if (!(seq contains elem)) this
            else new ThingSet(seq filterNot (elem ==): _*)
        def contains (elem: Thing) : Boolean = seq exists (elem ==)
        def iterator : Iterator[Thing] = seq.iterator
    }
    
    object ThingSet {
        def empty: ThingSet = new ThingSet()
        def newBuilder: Builder[Thing, ThingSet] = new SetBuilder[Thing, ThingSet](empty)
        def apply(elems: Thing*): ThingSet = (empty /: elems) (_ + _)
        def thingSetCanBuildFrom = new CanBuildFrom[ThingSet, Thing, ThingSet] {
            def apply(from: ThingSet) = newBuilder
            def apply() = newBuilder
        }
    }
    

提交回复
热议问题