我有以下代码以字母
打印1至9的数字class IntToNumber(num:Int) {
val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6" -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
def inLetters():String = {
digits.getOrElse(num.toString,"")
}
}
implicit def intWrapper(num:Int) = new IntToNumber(num)
(1 until 10).foreach(n => println(n.inLetters))
当我运行此代码时,我收到一条错误消息,指出该方法不适用于Long
Script.scala:9: error: value inLetters is not a member of Long
(1 until 10).foreach(n => println(n.inLetters))
^
one error found
将最后一行更改为
(1 until 10).foreach(n => println(n.toInt.inLetters))
工作正常..
有人可以帮助我理解为什么那个(1到10)范围返回Long而不是int?
答案 0 :(得分:14)
我已将隐式转换的名称更改为intWrapperX
。以下会话显示了修复示例。
问题是,创建intWrapper
对象所需的scala.Predef.intWrapper(i:Int): RichInt
阴影Range
。我将解释为何转换为Long
(或推定RichLong
)的问题留给了评论者。
scala> :paste
// Entering paste mode (ctrl-D to finish)
class IntToNumber(num:Int) {
val digits = Map("1" -> "one", "2" -> "two", "3" -> "three", "4" -> "four", "5" -> "five", "6" -> "six", "7" -> "seven", "8" -> "eight", "9" -> "nine")
def inLetters():String = {
digits.getOrElse(num.toString,"")
}
}
implicit def intWrapperX(num:Int) = new IntToNumber(num)
// Exiting paste mode, now interpreting.
defined class IntToNumber
intWrapperX: (num: Int)IntToNumber
scala> (1 until 10).foreach(n => println(n.inLetters))
one
two
three
...