- I have 3 Scala classes (A,B,C).
- I have one implicit conversion from A -> B and one from B -> C.
At some point in my code, I want to call a C method on A. Is this possible?
One fix I came up is to have a conversion from A -> C but that seems somewhat redundant.
Note:
- When I call B methods on A it works.
- When I call C methods on B it works.
- When I call C methods on A it says that it didn’t find the method in the body of A
Thanks …
It does seem somewhat redundant, but the
A -> Cconversion is exactly what you should supply. The reason is that if implicits are rare, transitive chains are also rare, and are probably what you want. But if implicits are common, chances are you’ll be able to turn anything into anything (or, if you add a handy-looking implicit, suddenly all sorts of behaviors will change because you’ve opened up different pathways for implicit conversion).You can have Scala chain the implicit conversions for you, however, if you specify that it is to be done. The key is to use generics with
<%which means “can be converted to”. Here’s an example: