隐式转换中的隐式参数
我试图在语言规范中找到应该告诉我这些隐式转换不起作用的位置:
scala> implicit def listToAlternativeList[F,T](xs: List[F])(implicit conv: (F) => T) = xs map conv
listToAlternativeList: [F,T](xs: List[F])(implicit conv: (F) => T)List[T]
scala> implicit def int2string(i: Int) = i.toString
int2string: (i: Int)java.lang.String
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> val l2: List[String] = listToAlternativeList[Int,String](l)
l2: List[String] = List(1, 2, 3)
scala> val l2: List[String] = listToAlternativeList(l)
l2: List[String] = List(1, 2, 3)
scala> val l2: List[String] = l
<console>:10: error: type mismatch;
found : List[Int]
required: scala.List[String]
val l2: List[String] = l
^
基本上,我想要的就是将某种类型的列表分配给声明为的变量另一种类型并开始隐式转换。这显然不起作用。我可以想出解决这个问题的方法,但我只是讨厌我不理解这里工作的一般规则。有人吗?
I'm trying to find the place in the language specification that should have informed me that these kind of implicit conversions don't work:
scala> implicit def listToAlternativeList[F,T](xs: List[F])(implicit conv: (F) => T) = xs map conv
listToAlternativeList: [F,T](xs: List[F])(implicit conv: (F) => T)List[T]
scala> implicit def int2string(i: Int) = i.toString
int2string: (i: Int)java.lang.String
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> val l2: List[String] = listToAlternativeList[Int,String](l)
l2: List[String] = List(1, 2, 3)
scala> val l2: List[String] = listToAlternativeList(l)
l2: List[String] = List(1, 2, 3)
scala> val l2: List[String] = l
<console>:10: error: type mismatch;
found : List[Int]
required: scala.List[String]
val l2: List[String] = l
^
Basically, all I want is to assign a List of a certain type to a variable that is declared to be of another type and get the implicit conversions kicking in. It obviously doesn't work. I can come up with ways to work around that, but I just hate it that I don't understand the general rule at work here. Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
隐式视图本身可能需要隐式参数。例如:
您的情况会发生什么?好吧,让我们用这个脚本的 scala -Ytyper-debug -Xlog-implicits 来看看幕后:
编译器然后解释:
我不太确定这是一个错误还是功能。但也许这个输出将帮助其他人进一步阐明这个问题。
It is possible for an implicit view to to itself require an implicit parameter. For example:
What happens in your case? Well, let's look behind the curtains with
scala -Ytyper-debug -Xlog-implicits
with this script:The compiler then explains:
I'm not quite sure if this is a bug or feature. But maybe this output will help someone else illuminate the matter further.