score:0

First, I can't get your first "obviously not safe" example to do anything:

import language.implicitConversions

object Test {
  implicit def chain[A, B, C](a: A)(implicit ab: A => B, bc: B => C): C = bc(ab(a))

  case class X()
  case class Y()
  case class Z()

  implicit def xy(x: X) = Y()
  implicit def yz(y: Y) = Z()

  val z: Z = X()
}

...

type mismatch;
  found   : Test.X
  required: Test.Z
   val z: Z = X()
               ^

Next, the obvious "catch" in your second example is that it doesn't compile. Did you actually try it? Regardless, after "fixing" it, it still doesn't do what you want:

import language.implicitConversions

class Convert[A, B](val convert: A => B) extends AnyVal
trait Convert0 {
  implicit def convert[A, B](implicit ab: A => B): Convert[A, B] = new Convert(ab)
  implicit def convert[A, B, C](implicit ab: Convert[A, B], bc: B => C): Convert[A, C] = new Convert(ab.convert andThen bc)
}
object Convert extends Convert0 {
  implicit def convert[A, B](a: A)(implicit convert: Convert[A, B]): B = convert.convert(a)
}

object Test {
  case class X()
  case class Y()
  case class Z()

  implicit def xy(x: X) = Y()
  implicit def yz(y: Y) = Z()

  val z: Z = X()
}

This gives the same type mismatch error. To my knowledge, if you want implicit conversions to chain, you have to be explicit about it:

import language.implicitConversions

object test {
  case class X()
  case class Y()
  case class Z()

  // anything convertible to X is convertible to Y
  implicit def xy[A <% X](x: A) = Y()

  // anything convertible to Y is convertible to Z
  implicit def yz[B <% Y](y: B) = Z()

  val z: Z = X()
}

Related Query

More Query from same tag