以下片段是否有问题: -
object Imp {
implicit def string2Int(s: String): Int = s.toInt
def f(i: Int) = i
def main(args: Array[String]) {
val n: Int = f("666")
}
}
Run Code Online (Sandbox Code Playgroud)
我从2.8编译器中得到以下内容: -
信息:编译完成时出现1错误和0警告
信息:1错误
信息:0警告
...\scala-2.8-tests\src\Imp.scala
错误:错误:第(4)行错误:类型不匹配;
found:
需要字符串:?{val toInt:?}
请注意,隐式转换不适用,因为它们不明确:
对象Imp中的方法string2Int类型(s:String)Int
和对象Prementf中的方法augmentString类型(x:String) scala.collection.immutable.StringOps
是可能的转换函数从String到?{val toInt:?}
隐式def string2Int(s:String):Int = s.toInt
Dan*_*ral 24
发生的事情是Java没有定义一个toInt方法String.在Scala中,定义该方法的是类StringOps(Scala 2.8)或RichString(Scala 2.7).
另一方面,也有一个方法toInt可用Int(通过另一个隐式,也许?),因此编译器不知道是StringOps通过定义的隐式转换字符串,还是Int通过自己的隐式转换.
要解决它,请显式调用隐式.
object Imp {
implicit def string2Int(s: String): Int = augmentString(s).toInt
def f(i: Int) = i
def main(args: Array[String]) {
val n: Int = f("666")
}
}
Run Code Online (Sandbox Code Playgroud)
目前已经在范围上的隐式转换,从scala.Predef.您不需要声明自己的隐式转换来向a添加toInt方法String.你有3个选择(我会选择最后一个!):
asIntPredeftoInt与scala库捆绑在一起的需要注意的是斯卡拉只会让使用在范围内的隐式转换,如果它是独一无二的.