Scala的理解:生命特征还是语法糖? [英] Scala's for-comprehensions: vital feature or syntactic sugar?

查看:74
本文介绍了Scala的理解:生命特征还是语法糖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次开始研究Scala时,我很喜欢理解.它们似乎有点像我从Java 5所熟悉的foreach循环,但是有功能上的限制和很多甜美的语法上的美感.

When I first started looking at Scala, I liked the look of for-comprehensions. They seemed to be a bit like the foreach loops I was used to from Java 5, but with functional restrictions and a lot of sweet syntactic niceness.

但是当我吸收了Scala风格后,发现每次使用强制转换时,我都会使用mapflatMapfilterreduceforeach.这样一来,对于我来说,代码的意图就更加清晰了,潜在的隐患更少了,而且它们通常也是较短的代码.

But as I've absorbed the Scala style, I find that every time I could use a for-comprension I'm using map, flatMap, filter, reduce and foreach instead. The intention of the code seems clearer to me that way, with fewer potential hidden surprises, and they're usually shorter code too.

据我所知,反感总是被归纳为这些方法,所以我想知道:它们实际上是干什么的?我是否缺少一些功能评估(这不是第一次)?理解会做其他功能无法做到的事情,还是至少会变得笨拙?它们在特定的用例下会发光吗?真的只是个人喜好吗?

As far as I'm aware, for-comprehensions are always compiled down into these methods anyway, so I'm wondering: what are they actually for? Am I missing some functional revalation (it wouldn't be the first time)? Do for-comprehensions do something the other features can't, or would at least be much clumsier at? Do they shine under a particular use case? Is it really just a matter of personal taste?

推荐答案

请参考此问题.简短的答案是,理解可以更容易理解.特别是,如果您有许多嵌套的生成器,那么您正在执行的操作的实际范围将变得更加清晰,并且您不需要巨大的缩进.

Please refer to this question. The short answer is that for-comprehensions can be more readable. In particular, if you have many nested generators, the actual scope of what you are doing becomes more clear, and you don't need huge indents.

这篇关于Scala的理解:生命特征还是语法糖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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