|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: "Restrictions to Implicit Conversions" |
| 4 | +--- |
| 5 | + |
| 6 | +Previously, an implicit value of type `Function1`, or any of its subtypes |
| 7 | +could be used as an implicit conversion. That is, the following code would compile |
| 8 | +even though it probably masks a type error: |
| 9 | + |
| 10 | + implicit val m: Map[String, Int] = Map(1 -> "abc") |
| 11 | + |
| 12 | + val x: String = 1 // scalac: assigns "abc" to x |
| 13 | + // Dotty: type error |
| 14 | + |
| 15 | +By contrast, Dotty only considers _methods_ as implicit conversions, so the |
| 16 | +`Map` value `m` above would not qualify as a conversion from `String` to `Int`. |
| 17 | + |
| 18 | +To be able to express implicit conversions passed as parameters, `Dotty` |
| 19 | +introduces a new type |
| 20 | + |
| 21 | + abstract class ImplicitConverter[-T, +U] extends Function1[T, U] |
| 22 | + |
| 23 | +Implicit values of type `ImplicitConverter[A, B]` do qualify as implicit |
| 24 | +conversions. It is as if there was a global implicit conversion method |
| 25 | + |
| 26 | + def convert[A, B](x: A)(implicit converter: ImplicitConverter[A, B]): B = |
| 27 | + converter(x) |
| 28 | + |
| 29 | +(In reality the Dotty compiler simulates the behavior of this method directly in |
| 30 | +its type checking because this turns out to be more efficient). |
| 31 | + |
| 32 | +In summary, previous code using implicit conversion parameters such as |
| 33 | + |
| 34 | + def useConversion(implicit f: A => B) { |
| 35 | + val y: A = ... |
| 36 | + val x: B = a // error under Dotty |
| 37 | + } |
| 38 | + |
| 39 | +is no longer legal and has to be rwritten to |
| 40 | + |
| 41 | + def useConversion(implicit f: ImplicitConverter[A, B]) { |
| 42 | + val y: A = ... |
| 43 | + val x: B = a // OK |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
0 commit comments