An implicit conversion function example in Scala/Dotty

Here’s a quick example of how to write an implicit conversion function in Scala/Dotty. Note that this has been updated with the latest syntax in late November, 2020:

// define a conversion from String to Int
given Conversion[String, Int] = Integer.parseInt(s)

// this import seems to still be needed
import scala.language.implicitConversions

// define a method that takes an Int
def plus1(i: Int) = i + 1

// give it a String instead
plus1("1")

I just tested that code with the Scala 3.0.0-M1 compiler, and it works as shown.

The earlier implicit conversion function syntax

This was an earlier Scala 2 and/or Dotty approach that has been changed for Scala 3:

import MyImplicitMethods.personToEmployee
import scala.language.implicitConversions

object ImplicitsTest1 extends App {

    val p = Person("Barb Saxet")
    val e: Employee = p

    println(s"Employee: $e")

}

object MyImplicitMethods {
    implicit def personToEmployee(p: Person): Employee = Employee(p.name)
}

case class Employee (name: String)
case class Person (name: String)

As shown, I import scala.language.implicitConversions to make this work. That’s needed if you want to get rid of this Scala/Dotty compiler warning message:

[info] Compiling 1 Scala source to /Users/al/ImplicitConversions/target/scala-0.11/classes ...
[warn] -- Feature Warning: /Users/al/Projects/ImplicitConversions/Test1.scala:9:22 
[warn] 9 |    val e: Employee = p
[warn]   |                      ^
[warn]   |Use of implicit conversion method personToEmployee in object MyImplicitMethods should be enabled
[warn]   |by making the implicit value scala.language.implicitConversions visible.
[warn]   |This can be achieved by adding the import clause 'import scala.language.implicitConversions'
[warn]   |or by setting the compiler option -language:implicitConversions.
[warn]   |See the Scala docs for value scala.language.implicitConversions for a discussion
[warn]   |why the feature should be explicitly enabled.
[warn] -- Feature Warning: /Users/al/Projects/ImplicitConversions/Test1.scala:16:17 
[warn] 16 |    implicit def personToEmployee(p: Person): Employee = Employee(p.name)
[warn]    |                 ^
[warn]    |Definition of implicit conversion method personToEmployee should be enabled
[warn]    |by making the implicit value scala.language.implicitConversions visible.
[warn]    |This can be achieved by adding the import clause 'import scala.language.implicitConversions'
[warn]    |or by setting the compiler option -language:implicitConversions.
[warn]    |See the Scala docs for value scala.language.implicitConversions for a discussion
[warn]    |why the feature should be explicitly enabled.
[warn] two warnings found

Note that you get that warning because, as the implicit conversions page on the Scala Tour states, “implicit conversions can have pitfalls if used indiscriminately.”