Scala“<-"表示理解 [英] Scala "<-" for comprehension

查看:94
本文介绍了Scala“<-"表示理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现Scala总是对任何事物都有自然的解释".总是像哦,但这只是在带有该参数的那个对象上调用的函数".从某种意义上说,没有什么是我们从其他语言中了解到的真正的编译器魔术.

I have found that Scala always has a "natural explanation" to anything. Always something like "ohh, but that's just a function being called on this and that object with this and that parameter". In a sense, nothing is really compiler-magic as we know it from other languages.

我的问题是在以下代码中使用的 <- 运算符:

My question is on the <- operator as used in the following code:

for(i <- 0 to 10) println(i)

在此示例中,我可以看到它被重写为类似以下内容:

In this example I can see it being rewritten to something like:

0.to(10).foreach((i:Int)=>println(i))

但这不能解释 i 是如何被带入foreach函数内部的匿名函数的.在编写 i 时,它不是对象,也不是声明的变量.那么,它是什么,以及它如何被延续到foreach的内部?

but this doesn't explain how the i got carried into the anonymous function inside the foreach function. At the point where you write i it is not an object, and not yet a declared variable. So what is it, and how is it being carried over to the inside of foreach?

我的猜测是,我终于发现了一些实际上是编译器魔术

My guess is that I finally discovered something which is in fact compiler magic

感谢您的时间.

为了澄清,我的问题是:<-运算符如何在代码的第一行中工作,因为我不是可在其上调用它的函数的对象.

To clarify, my question is: how does the <- operator work in the 1st line of code since i is not an object on which it can be called as a function.

推荐答案

<-是语言定义的关键字符号,=>也是,但与->(已定义的符号)形成鲜明对比.由于它是Scala基本语法的一部分,因此可以用来创建绑定(对于您的示例中的i而言),这是用户定义的构造无法完成的.

<- is a language-defined keyword symbol, as is => but in distinct contrast to -> (which is a defined symbol). Because it is part of the basic Scala grammar, it can be used to create bindings (for the i in your example) which is something that cannot be done by user-defined constructs.

这篇关于Scala“&lt;-"表示理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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