Scala中隐含的碰撞

Han*_*örr 1 scala implicit implicit-conversion

以下Scala代码正常工作:

val str1 = "hallo"
val str2 = "huhu"
val zipped: IndexedSeq[(Char, Char)] = str1.zip(str2)
Run Code Online (Sandbox Code Playgroud)

但是,如果我导入隐式方法

implicit def stringToNode(str: String): xml.Node = new xml.Text(str)
Run Code Online (Sandbox Code Playgroud)

然后Scala(2.10)编译器显示错误: value zip is not a member of String

似乎存在stringToNode某种方式块的隐式转换str1str2WrappedString.为什么?有没有一种方法来修改stringToNode这样的zip工作,但是stringToNode当我调用一个需要带Node参数的函数时仍然使用String

Fel*_*lix 6

你这里有含糊不清的含义.StringOps和xml.Node都有zip方法,因此隐式转换是不明确的,无法解析.我不知道为什么它没有给出更好的错误信息.

以下是一些备份链接:http: //www.scala-lang.org/api/current/index.html#scala.collection.immutable.StringOpshttp://www.scala-lang.org/api /current/index.html#scala.xml.Node

编辑:它是StringOps,而不是WrappedString,更改了链接:)看看Predef:http://www.scala-lang.org/api/current/index.html#scala.Predef $来查看Scala中的预定义含义.

在这种情况下,我会避免使用含义.您需要2个不同的隐式转换,它们都提供相同名称的方法(zip).我不认为这是可能的.此外,如果您导入xml.Text,您可以转换为Text(str)哪个应该简洁到任何人.如果你必须将这个隐式转换为xml.Node,我会将隐式def打包到一个对象中,然后只在你需要它的地方导入它以使你的代码可读,并且可能避免在你需要的地方发生冲突拉链.但基本上,我会非常避免使用implicits只是为了方便转换.