Implicit conversion between Scala collection types
Posted
by
ebruchez
on Stack Overflow
See other posts from Stack Overflow
or by ebruchez
Published on 2011-01-13T00:13:35Z
Indexed on
2011/01/13
23:53 UTC
Read the original article
Hit count: 208
I would like to implicitly convert between the Scala XML Elem object and another representation of an XML element, in my case dom4j Element. I wrote the following implicit conversions:
implicit def elemToElement(e: Elem): Element = ... do conversion here ...
implicit def elementToElem(e: Element): Elem = ... do conversion here ...
So far so good, this works.
Now I also need collections of said elements to convert both ways. First, do I absolutely need to write additional conversion methods? Things didn't seem to work if I didn't.
I tried to write the following:
implicit def elemTToElementT(t: Traversable[Elem]) = t map (elemToElement(_))
implicit def elementTToElemT(t: Traversable[Element]) = t map (elementToElem(_))
This doesn't look too ideal because if the conversion method takes a Traversable, then it also returns a Traversable. If I pass a List, I also get a Traversable out. So I assume the conversion should be parametrized somehow.
So what's the standard way of writing these conversions in order to be as generic as possible?
© Stack Overflow or respective owner