admin管理员组文章数量:1402923
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
1 Answer
Reset to default 6given 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.
本文标签:
版权声明:本文标题:How to specify Scala 3 `scala.Conversion` when the types being converted take an arbitrary type parameter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744361272a2602557.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论