IOD*_*DEV 0 autoboxing numerical types scala numerical-methods
我试图理解Scala for-loop隐式盒子/拆箱"数字"类型的行为.为什么这两个首先失败但其余的失败?
1)失败:
scala> for (i:Long <- 0 to 10000000L) {}
<console>:19: error: type mismatch;<br>
found : Long(10000000L)
required: Int
for (i:Long <- 0 to 10000000L) {}
^
Run Code Online (Sandbox Code Playgroud)
scala> for (i <- 0 to 10000000L) {}
<console>:19: error: type mismatch;
found : Long(10000000L)
required: Int
for (i <- 0 to 10000000L) {}
^
Run Code Online (Sandbox Code Playgroud)
scala> for (i:Long <- 0L to 10000000L) {}
scala> for (i <- 0L to 10000000L) {} scala> for (i:Long <- 0 to 10000000L) {}
<console>:19: error: type mismatch;<br>
found : Long(10000000L)
required: Int
for (i:Long <- 0 to 10000000L) {}
^
Run Code Online (Sandbox Code Playgroud)
4)作品:
scala> for (i <- 0 to 10000000L) {}
<console>:19: error: type mismatch;
found : Long(10000000L)
required: Int
for (i <- 0 to 10000000L) {}
^
Run Code Online (Sandbox Code Playgroud)
它与for循环无关:
0 to 1L //error
0 to 1 //fine
0L to 1L //fine
0L to 1 //fine
Run Code Online (Sandbox Code Playgroud)
这只是因为to可用的方法Int需要一个Int作为其参数.因此,当你给它一个Long它不喜欢它,你会得到一个错误.
以下是该to方法的定义,可在RichInt以下位置找到:
def to(end: Int): Range.Inclusive = Range.inclusive(self, end)
Run Code Online (Sandbox Code Playgroud)