4

If I have an implicit from A to B, how can I auto-get implicits from F[A] to F[B]?

For example, if I have implicit toInt[A](l: List[A]) = l.size and now I want to have an implicit from (List[A], Int) to (Int, Int) which reuses the toInt implicit. Is that even possible in Scala?

pathikrit
  • 32,469
  • 37
  • 142
  • 221

1 Answers1

4

Implicits can use other implicits to convert values. So given your toInt:

implicit def toInt[A](l: List[A]): Int = l.size

We can define an implicit conversion for converting the first element of a 2-tuple to Int, e.g. (List[Int], Int) to (Int, Int):

implicit def tupleConvert[A <% Int, C](x: (A, C)): (Int, C) = (x._1, x._2)

The A <% Int declares a view bound, requiring that an implict conversion from A to Int be available in the calling scope.

It might seem like the following would be possible:

implicit def tupleConvert2[A <% B, B, C](x: (A, C)): (B, C) = (x._1, x._2)

allowing us to convert any 2-tuple of type (A, C) to (B, C) given a conversion from A to B. However, because of the way Scala resolves type parameters for implicits this does not work*.

*(I think this may be a bug, it looks a lot like SI-2046, which is a duplicate of SI-3340, which is still open)

wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52