3

Considering this code:

def myMap[T, S](seq: S)(implicit ev: S <:< Seq[T]): S =
  seq.map { x => x }

The compiler complains:

error: type mismatch;
found   : Seq[T]
required: S

Obviously seq.map { x => x } returns a Seq[T], instead of S.

But S is a subclass of Seq[T], and map should be able to build an S to another S.

How to write such a function receiving any Seq and return original type, not just Seq?

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164
  • 1
    I think you will have to venture into `CanBuildFrom` territory. If you take a look at full `map` signature, for `List` (for example) it looks like this: `def map[B, That](f: (A) => B)(implicit bf: CanBuildFrom[List[A], B, That]): That`; that should give you a slight hint. – Patryk Ćwiek Dec 22 '13 at 11:42
  • @0__ that works but... do I have to write such long code for every single method I want to apply on generic collections?! – Lai Yu-Hsuan Dec 22 '13 at 12:42
  • @LaiYu-Hsuan if you want that method to return the same collection type, yes, you need a builder factory (`CanBuildFrom`). – 0__ Dec 22 '13 at 16:47

0 Answers0