scalas组合隐式转换的能力有哪些限制

scalas组合隐式转换的能力有哪些限制,scala,implicit,Scala,Implicit,在以下代码中,最后一行不起作用: 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 = t

在以下代码中,最后一行不起作用:

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")
}
我不明白为什么不-它知道如何转换(B,B)->C和String->B,它可以转换(String,String)->(B,B)。所有的部分都在那里,但是如果没有显式的(String,String)->C方法,它就不能工作


有什么解决方法吗?

编译器将只搜索直接转换,它不知道如何组合2个隐式转换以达到所需的类型。解决方法是编写第三个从字符串元组到C的隐式转换,或者将中间B存储在一个值中。

基于另一个,可以这样做:

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")
}
对象测试模板{
隐式def str2b(s:字符串):B=B(s)

隐式def in2b[B1 B)

罗宾-完全是这样,那里的答案正是我所需要的(即使看起来很像伏都教…)。我应该完全删除这个问题,还是留下一个指向现有答案的指针?我认为这个问题更简洁,但另一个问题有真正的答案。