简体   繁体   English

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

[英]Behavior of Scala for/comprehension implicit transformation of numerical types?

I'm trying to understand the behavior of Scala for-loop implicit box/unboxing of "numerical" types. 我试图了解Scala for循环“数字”类型的隐式装箱/拆箱的行为。 Why does the two first fail but not the rest? 为什么前两个失败而不是其他失败?

1) Fails: 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) {} ^ 

2> Fails: 2>失败:

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

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

3) Works: 3)作品:

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

4) Works: 4)作品:

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

It has nothing to do with the for-loop: 它与for循环无关:

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

It's just because the to method available to Int expects an Int as its argument. 这只是因为Int可用的to方法期望将Int作为其参数。 So when you give it a Long it doesn't like it, and you get an error. 因此,当您给它Long它会不喜欢它,并且会出现错误。

Here's the definition of the to method, found on RichInt : 这是RichIntto方法的定义:

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

The desugaring and implicit transformation of numerical types is inconsistent ie differ between the "for/comprehension" expressions compared to assignment operations. 数字类型的删除和隐式转换是不一致的,即与赋值操作相比,“ for / compresion”表达式之间存在差异。 Please feel free to prove otherwise or at least point where the argument below is flawed: 请随时证明否则,或至少指出以下论点有缺陷的地方:

In fact, during numeric assignment the Destination type is dominant. 实际上,在数字分配过程中,“ 目标”类型占主导。

var l:Long = 0 becomes: var l:Long = 0变为:
val l: Long = 0L

var l:Long = 0.toInt becomes: var l:Long = 0.toInt变为:
var l: Long = 0.toInt.toLong

During "for/comprehension" expressions the Source type is dominant: 在“用于/理解”表达式中,“ 源”类型占主导地位:

for (i:Long <- 0 to 1000000000L) { } becomes: for (i:Long <- 0 to 1000000000L) { }变为:
0.to(1000000000L).foreach(((i: Long) => ()))

for (i <- 0L to 1000000000L) { } becomes: scala.this.Predef.longWrapper(0L).to(1000000000L).foreach[Unit](((i: Long) => ())) for (i <- 0L to 1000000000L) { } scala.this.Predef.longWrapper(0L).to(1000000000L).foreach[Unit](((i: Long) => ())) for (i <- 0L to 1000000000L) { }变为: scala.this.Predef.longWrapper(0L).to(1000000000L).foreach[Unit](((i: Long) => ()))

(ps: output generated with the "-Xprint:typer -e" compiler flag. ds) (ps:使用“ -Xprint:typer -e”编译器标志生成的输出。ds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM