【发布时间】:2012-01-30 07:50:03
【问题描述】:
我在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
}
编译成功。谁能告诉我这两者有什么区别?
【问题讨论】:
-
不知道确切的答案,但我想Predef中有一个隐式转换字符串-> int。因此,添加该类型的新转换会使事情变得模棱两可。