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

编程入门 行业动态 更新时间:2024-10-14 00:25:00
本文介绍了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 对数值类型的/理解隐式转换的行为?

本文发布于:2023-07-14 10:16:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104080.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数值   类型   隐式   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!