Say I have an implicit conversion:
implicit def aToB(a: A):B={
...
}
How can I get this implicit conversion to work on the elements of a List?
If I have:
val listOfA: List[A] ...
and I have a function that takes a List of B, is it possible to let Scala implicitly convert all of the elements from A’s to B’s?
Without implicit conversions, the conversion might look like:
lisftOfA.map(a => new B(a.someValue, a.anotherValue))
But I would love for this to happen like ‘magic’… is that too much to ask.
Here are a few alternatives you might wish to consider:
1. Use a view bound
If it’s possible to change the function that takes a List of Bs, this would be the simplest solution. Modify it to accept a List of things that can be converted to Bs. That is,
would become
Then, you can just call the function with listOfA:
2. Introduce a conversion method
This is similar to Rogach’s first solution, except that the outer conversion is non-implicit:
Then at your function’s call-site, you would write
Like Rogach’s second solution, this is bit safer than bringing in an implicit conversion.
3. Introduce an implicit conversion
This is equivalent to Rogach’s first solution, but the notation is a bit nicer (IMO).
If this conversion is in scope at your call-site, you can just call your function with the listOfA:
Parting Thoughts
It’s interesting to consider how to solve this problem in a general way. What if I want to define my conversion method so that it can handle any type that implements the
mapmethod? i.e.,This won’t work, of course, since nothing in the signature expresses the constraint that
Cmust implementmap. As far as I know, expressing this constraint is fairly involved and cannot be done in a way that provides out-of-the-box support for any type that implementsmap. See Type-safe Scala sequence comprehensions.