斯卡拉“<-"为了理解 [英] Scala "<-" for comprehension

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

问题描述

我发现 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

感谢您的时间.

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

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.

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

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