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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744361272a4570483.html
评论列表(0条)