4

暗黙の from toがある場合、暗黙の from AtoBを自動取得するにはどうすれF[A]ばよいF[B]ですか?

たとえば、暗黙のfromを再利用するimplicit toInt[A](l: List[A]) = l.size暗黙のfrom (List[A], Int)toが必要な場合。それはScalaでも可能ですか?(Int, Int)toInt

4

1 に答える 1

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)

于 2014-04-28T02:51:17.810 に答える