scalaimplicit-conversionimplicitscala-3type-parameter

How to specify Scala 3 `scala.Conversion` when the types being converted take an arbitrary type parameter


From the Scala 3 docs on implicit conversions:

In Scala 3, an implicit conversion from type S to type T is defined by a given instance of type scala.Conversion[S, T]. For compatibility with Scala 2, it can also be defined by an implicit method.

For example, this code defines an implicit conversion from Int to Long:

given int2long: Conversion[Int, Long] with
  def apply(x: Int): Long = x.toLong

This would be the preferred syntax in Scala 3, while the old Scala 2 syntax would be:

implicit def int2long(x: Int): Long = x.toLong

However, there's a case the old Scala 2 syntax supports, that I can not see how write in the new Scala 3 syntax: what if the types being converted take an arbitrary type parameter? ie you need to transform a Foo[A] to a Bar[A]?

In Scala 2 this would be:

implicit def foo2bar[A](x: Foo[A]): Bar[A] = ???

In Scala 3, where would the type parameter A be identified?

For instance, this definitely doesn't work:

given [A] foo2bar: Conversion[Foo[A], Bar[A]] with
  def apply(x: Int): Long = ???

Solution

  • given foo2bar[A]: Conversion[Foo[A], Bar[A]] with
      def apply(x: Foo[A]): Bar[A] = ???
    

    As mentioned in the comments by @Dmytro, the name foo2bar can also be ommitted.