1

In the following code, the last line doesn't work:

case class B(v:String)
case class C(s:B,r:B)

object TestImplicits {
  implicit def str2b(s:String) : B = B(s)
  implicit def in2b(i:(B,B)) :C = C(i._1,i._2)

  val t : B = "hello"
  val tb : (B,B) = ("hello","there")
  val c : C = tb
  val cb : C = (B("hello"),B("there"))
  val n : C = ("hello","there")
}

I don't understand why not - it knows how to convert (B,B)->C, and String->B, it can turn (String,String) -> (B,B). All the pieces are there, but it doesn't work without an explicit (String,String)->C method.

Is there any workaround?

mo-seph
  • 6,073
  • 9
  • 34
  • 35
  • Robin - it totally is, and the answer there is exactly what I needed (even if it looks pretty voodoo...). Should I delete this question entirely, or leave it with a pointer to the existing answer? I think this question is more concise, but the other one has the real answer in. – mo-seph Dec 17 '13 at 23:47

2 Answers2

1

Based on the other linked question, this can be done like this:

object TestImplicits {
  implicit def str2b(s:String) : B = B(s)
  implicit def in2b[B1 <% B](i:(B1,B1)) :C = C(i._1,i._2)

  val t : B = "hello"
  val tb : (B,B) = ("hello","there")
  val c : C = tb
  val cb : C = (B("hello"),B("there"))
  val n : C = ("hello","there")
}

Note that the signature for in2b has now changed - it is equivalent to implicit def in2b(i:(B,B))(implicit ev: B1=>B)

Community
  • 1
  • 1
mo-seph
  • 6,073
  • 9
  • 34
  • 35
0

The compiler will only search a direct conversion, it does not know how to compose 2 implicit conversions to reach the desired type. The workaround is to write a third implicit conversion from a tuple of strings to C, or to store the intermediate Bs in a value.

vptheron
  • 7,426
  • 25
  • 34