Scala的行为/理解数值类型的隐式变换?

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)

dhg*_*dhg 8

它与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)

  • `scalac -print`不打印scala - > java转换,因为scala代码没有被转换为java.`scalac -print`打印scala代码,最终转换为字节码.仅仅为了理解是不可能的.但基本上所有for-comprehension都被转换为嵌套的flatMaps,其中最里面的是一个简单的map. (2认同)