Extending Scala collections

后端 未结 4 2128
执念已碎
执念已碎 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:27

    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]] {...}
    }
    

提交回复
热议问题