Returning original collection type in generic method

前端 未结 3 467
滥情空心
滥情空心 2020-12-01 07:06

Say we want to make a function like minBy that returns all elements of equal minimalism in a collection:

def multiMinBy[A, B: Ordering](xs: Trav         


        
3条回答
  •  甜味超标
    2020-12-01 07:36

    I think Miles Sabin solution is way too complex. Scala's collection already have the necessary machinery to make it work, with a very small change:

    import scala.collection.TraversableLike
    def multiMinBy[A, B: Ordering, C <: Traversable[A]]
                  (xs: C with TraversableLike[A, C])
                  (f: A => B): C = {
      val minVal = f(xs minBy f)
      xs filter (f(_) == minVal)
    }
    

提交回复
热议问题