加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么这种隐式转换是非法的?

发布时间:2020-12-16 09:35:00 所属栏目:安全 来源:网络整理
导读:我在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 conv
我在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
           ^

如果我删除返回类型,只要这样声明:

implicit def strToInt2(str: String) = {
    str.toInt
  }

它成功编译有谁能告诉我两者有什么区别?

解决方法

好的,我们从头开始,为什么在第一种情况下失败?

>您尝试定义一个将String转换为Int的隐式方法,并将其调用为Int。
>不幸的是,toInt不是String类的一部分。因此,编译器需要在具有toInt:Int方法的东西中找到一个隐式来转换str。
>幸运的是,Predef.augmentString将一个String转换成一个StringOps,它具有这样一种方法。
>但是Int类型也有这样一种方法,AS定义了一个返回类型,strToInt2方法可以递归调用,并且由于该方法是隐式的,它可以应用于使用toInt:Int函数来转换东西。
>编译器不知道使用哪个隐式方法(在你的和Predef.augmentString之间,并引发一个错误。

在第二种情况下,当您省略返回类型时,strToInt2函数不能是递归的,并且不再有两个转换String的候选项。

但是,如果在这个定义之后,你尝试:“2”.toInt,错误是回来的:你现在有两种方法来获得一个有一个toInt:Intfunction的东西,当你有一个String。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读