"one", "2" -> "two", "-6ren">
gpt4 book ai didi

标量范围返回Long而不是Int

转载 作者:行者123 更新时间:2023-12-04 03:30:06 25 4
gpt4 key购买 nike

我有以下代码以字母形式打印从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吗?

最佳答案

我已将您的隐式转换的名称更改为intWrapperX。以下 session 显示了固定的示例。

问题是,您的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
...

关于标量范围返回Long而不是Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9260782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com