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

From the Scala 3 docs on implicit conversions:In Scala 3, an implicit conversion from type S to type T

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 = ???

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 = ???
Share Improve this question edited Mar 21 at 10:50 Dmytro Mitin 51.8k3 gold badges32 silver badges73 bronze badges asked Mar 21 at 10:13 Roberto TyleyRoberto Tyley 25.4k12 gold badges75 silver badges105 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 6
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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744361272a4570483.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信