scala – 为什么这种隐式转换是非法的?
我在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。 在第二种情况下,当您省略返回类型时,strToInt2函数不能是递归的,并且不再有两个转换String的候选项。 但是,如果在这个定义之后,你尝试:“2”.toInt,错误是回来的:你现在有两种方法来获得一个有一个toInt:Intfunction的东西,当你有一个String。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |