Scala 对数值类型的/理解隐式转换的行为? [英] Behavior of Scala for/comprehension implicit transformation of numerical types?

查看:61
本文介绍了Scala 对数值类型的/理解隐式转换的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 Scala for-loop 隐式装箱/拆箱数字"类型的行为.为什么这两个先失败了,其余的没有?

I'm trying to understand the behavior of Scala for-loop implicit box/unboxing of "numerical" types. Why does the two first fail but not the rest?

1) 失败:

scala> for (i:Long <- 0 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) {}
                                  ^

2> 失败:

scala> for (i <- 0 to 10000000L) {}

scala> for (i <- 0 to 10000000L) {}

      <console>:19: error: type mismatch;
      found   : Long(10000000L)
      required: Int
          for (i <- 0 to 10000000L) {}
                         ^

3) 作品:

scala> for (i:Long <- 0L to 10000000L) {}

4) 作品:

scala> for (i <- 0L to 10000000L) {}

推荐答案

与for循环无关:

0 to 1L   //error
0 to 1    //fine
0L to 1L  //fine
0L to 1   //fine

这只是因为 Int 可用的 to 方法需要一个 Int 作为它的参数.所以当你给它一个 Long 它不喜欢它,你会得到一个错误.

It's just because the to method available to Int expects an Int as its argument. So when you give it a Long it doesn't like it, and you get an error.

这里是 to 方法的定义,在 RichInt 上找到:

Here's the definition of the to method, found on RichInt:

def to(end: Int): Range.Inclusive = Range.inclusive(self, end)

这篇关于Scala 对数值类型的/理解隐式转换的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆