Scala transitive implicit conversion

  • 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 the C method on A. Is this possible? One fix I came up with is a conversion from A → C, but that seems a bit redundant.

Note:

  • When I call methods B on A, it works.
  • When I call C methods on B, it works.
  • When I call C methods on A, it says that it did not find the method in body A

Thanks...

+6
source share
2 answers

This seems somewhat redundant, but the A -> C conversion is exactly what you have to provide. The reason is that if implications are rare, transition chains are also rare and you probably want to. But if implications are common, most likely you can turn anything into anything (or, if you add a convenient expression implicitly, suddenly all kinds of behavior will change because you opened different paths for implicit conversion).

You may have a Scala implicit conversion chain for you, however, if you specify that you need to do this. The key is to use generics with <% , which means "can be converted to." Here is an example:

 class Foo(i: Int) { def foo = i } class Bar(s: String) { def bar = s } class Okay(b: Boolean) { def okay = b } implicit def to_bar_through_foo[T <% Foo](t: T) = new Bar((t: Foo).foo.toString) implicit def to_okay_through_bar[U <% Bar](u: U) = new Okay((u: Bar).bar.length < 4) scala> (new Foo(5)).okay res0: Boolean = true 
+6
source

It seems you made a typo when you wrote the question. Did you mean to say that you have implicit conversions from A -> B and B -> C , and that you find the redundant transform A -> C ?

Scala has a rule that it will only apply one implicit conversion if necessary (but never two), so you cannot just expect Scala to magically compose A -> B and B -> C to convert you need. You will need to provide your own conversion A -> C This is not redundant.

+9
source

Source: https://habr.com/ru/post/909949/


All Articles