Scala 为什么这种类型的隐式转换是非法的?
我在scala中编写了以下隐式转换:Scala 为什么这种类型的隐式转换是非法的?,scala,implicit-conversion,Scala,Implicit Conversion,我在scala中编写了以下隐式转换: implicit def strToInt2(str: String):Int = { str.toInt } 但这也引发了编译错误: <console>:9: error: type mismatch; found : str.type (with underlying type String) required: ?{val toInt: ?} Note that implicit conversions are n
implicit def strToInt2(str: String):Int = {
str.toInt
}
但这也引发了编译错误:
<console>:9: error: type mismatch;
found : str.type (with underlying type String)
required: ?{val toInt: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method augmentString in object Predef of type (x: String)scala.collection.
immutable.StringOps
and method toi in object $iw of type (str: String)Int
are possible conversion functions from str.type to ?{val toInt: ?}
str.toInt
^
它编译成功。有谁能告诉我这两者的区别吗?好的,让我们从开头开始,为什么第一种情况下失败了:
字符串
转换为Int
,并为此调用toInt
toInt
不是String
类的一部分。因此,编译器需要在具有toInt:Int
方法的内容中找到隐式转换str
Predef.augmentString
将String
转换为StringOps
,它有这样一种方法Int
类型也有这样一个方法,当您定义一个返回类型时,可以递归调用strotint2
方法,并且由于该方法是隐式的,因此可以使用toInt:Int
函数应用它来转换某些内容Predef.augmentString
之间),并抛出错误strotint2
函数不能是递归的,并且不再有两个候选函数来转换字符串
但如果在此定义之后,您尝试:“2”.toInt
,错误又回来了:当您有一个字符串时,您现在有两种方法可以通过toInt:Int
函数获得某些内容,但我不知道确切的答案,但我假设Predef中有一个隐式转换字符串-/Int。因此,添加该类型的新转换会使事情变得不明确。那么…我们如何解决这个问题?我需要stringToInt
方法。我可以这样定义它:defstring2int(string:string):Int=Predef.augmentString(string).toInt
来解决歧义,但不幸的是,这破坏了同一范围内的显式“2.toInt
(它不再编译).有没有办法将隐式字符串->Int转换和显式String.toInt
都放在同一范围内?
implicit def strToInt2(str: String) = {
str.toInt
}