Scala隐式转换的问题分析-String隐式转换为Int
引出问题
首先来看一个需求:将String类型的数字赋值给Int类型的变量。
也就是这样:
val num:Int="20"
要想实现这样的效果,小伙伴们应该都能想到使用隐式方法
这个技能。许多小伙伴一鸡冻就撸出了如下的代码:
implicit def strToInt(str:String):Int= {
str.toInt
}
***友情提示:***隐式转换的代码要定义在object中哦~~~
定义了如上的隐式方法后,接下来我们来使用一下该隐式方法。接下来来一段完整代码尝尝:
object TestDemo {
def main(args: Array[String]): Unit = {
val num:Int = "20"
println(num)
}
/**
* 定义的隐式方法
* 该方法的功能是将String转成Int
* @param str 需要转换的字符串
* @return 返回 Int
*/
implicit def strToInt(str:String):Int= {
str.toInt
}
}
代码撸完,感觉还不错,接着我们运行以上代码:哐当,出错啦。。。。
控制台输出以下错误信息:
Error:(17, 5) type mismatch;
found : str.type (with underlying type String)
required: ?{
def 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 strToInt in object TestDemo of type (str: String)Int
are possible conversion functions from str.type to ?{
def toInt: ?}
str.toInt
Error:(17, 9) value toInt is not a member of String
str.toInt
大伙看错误信息中有个关键的单词ambiguous(模糊不清的,模棱两可的)
,以上错误信息的大致意思是说:
隐式转换在这里不适用了