Search code examples
scalaimplicit-conversionimplicit

Why are implicit conversion deprecated in scala?


Taken from "Scala with cats" (page 18):

Implicit Conversions
When you create a type class instance constructor using an implicit def, be sure to mark the parameters to the method as implicit pa­rameters. Without this keyword, the compiler won’t be able to fill in the parameters during implicit resolution. implicit methods with non‐implicit parameters form a different Scala pattern called an implicit conversion. This is also different from the previous section on Interface Syntax, because in that case the JsonWriter is an implicit class with extension methods. Implicit con­version is an older programming pattern that is frowned upon in mod­ern Scala code. Fortunately, the compiler will warn you when you do this. You have to manually enable implicit conversions by importing scala.language.implicitConversions in your file

Can anyone please sum up well why implicit conversion are deprecated? What were there limit or issues? Why the approach with implicit parameters is better?

Note I know how to use the modern approach well, including chaining implicit and all. I am just curious as to what was the issue and why it was deprecated.


Solution

  • As of Scala 3.3, implicit conversions are not deprecated.

    ... in Scala 2, implicit conversions were also used to provide additional members to closed classes (see Implicit Classes). In Scala 3, we recommend to address this use-case by defining extension methods instead of implicit conversions (although the standard library still relies on implicit conversions for historical reasons).

    Implicit conversions for extending closed classes have been replaced by extension methods but implicit conversions still exist and have their use.

    There are a couple of reasons to avoid implicit conversions:

    • It can be hard to read code that implicitly converts a value of one type to another. Often it is better to be explicit and convert it manually.
    • If an API expects you to make use of implicit conversions then it can be difficult to understand the error messages when the implicit conversion is not in scope.

    Because implicit conversions can have pitfalls if used indiscriminately the compiler warns in two situations:

    • when compiling a Scala 2 style implicit conversion definition.
    • at the call site where a given instance of scala.Conversion is inserted as a conversion.

    To turn off the warnings take either of these actions:

    • Import scala.language.implicitConversions into the scope of:
      • a Scala 2 style implicit conversion definition
      • call sites where a given instance of scala.Conversion is inserted as a conversion.
    • Invoke the compiler with -language:implicitConversions