How can I chain implicits in Scala? -



The broker-meri-library pattern gives me an underlying conversion from that class and appears in a class that a method is added Gives the one who executes the method.

Scala does not allow the conversion of two such errors, so I can not get a code from A to C A to b and the other built in B to c . Is there no way around this restriction?

There is a restriction on automatic conversions to add Scala to a method, which is to find ways to Will not apply more than one conversion in the try. For example:

  class A (val n: int) square b (val m: int, val n: int) square c (val m: int, val n: int, val o : Int) {def total = m + n + o} // indicates that it is easy to test the underlying def to A (n: int) to object the underlying conversion chaining restriction T1 {//: A = New A (n) implicit def aToB (A: A): B = new B (A, A) built-in def BTOC (B: B): C = new C (BM, BN, BM + BN) // printlane (5 Println (New A (5, 5) .total) println (New C (5, 5, 10) .total)}   

Edit: Scene 2.11 has been deprecated ('& lt;%') (You can use type class instead)

However, If an implicit definition is required for an underlying definition, see the additional underlying values ​​for the self (see bound), the scale will , as required, continue with the previous example:

  // def m [a & lt;% B] (m: a) // def m [A] (M: A) () Built-in ev: A => B) Object T2 {INSTRUMENT DEFUTE TO A (N: INTER): A = New A (N) Institute DEF ATOB [A1 and LT;% A] (A: A1): B = New B (A, A) ) Contained DEF BTOC [B1 and LT;% B] (B: B1): C = New C (BM, BN, BM + BN) // printlane in print (5) printlane (new A (5) total. ) Printalan (New B (5, 5). Bottle) Printlen (New C (5, 5, 10). Tolol)}   

"Magic!", You can say no . Here's how the compiler will translate each:

  Object T1 Translated {built-in def to a (n: int): A = New A (n) underlying def aToB (a: A) ): B = New B (A, A) Built-in BTOC (B: B): C = New C (BM, BN, BM + BN) // Scala will not printline it (BTOC (ATO (AATA) ) Total) println (BTOC (ATOB (New A (5)) Total) // Just this Printerian (BTOC (New B (5, 5)) Total) // No implicits required Println (new C (5, 5, 10) .teal)} Object T2 transorcrated {suggestion to a (n: int): A = new A (n) institute def ATOB [A1 and LT;% A] ( A: A1): B = New B (A, A) vested DEF BTOC [B1 and LT; B] B: B = C = New C (BM, BN, BM + BN) // Scala This printline (BTOC (5) (x = & gt; ATOB (x) (Y = & gt; toa (y) total) println (bToC (new A (5)) (x = & gt; aToB (x) (Identity) Total) println (BTOC (new B (5, 5)) (identity) .tool) // no implicits println (new c (5, 5, 10) .total)}   

Then, while bToC is being used as a built-in conversion, aToB < Being passed as / code> and toA impli

edit

related to interest Question:



Comments