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

我在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 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
      }