Scala - 中缀与点符号 [英] Scala - infix vs dot notation

查看:24
本文介绍了Scala - 中缀与点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有最佳实践?我一直在阅读 Odersky 等人的 Scala 书籍.并且似乎中缀用于许多 Collections API 函数,而 dot 保留用于程序员定义的函数.

Is there a best practice for one over the other? I've been reading the Scala book by Odersky, et al. and it seems like infix is used for a lot of the Collections API functions, whereas dot is reserved for programmer-defined functions.

推荐答案

我个人对此没有任何硬性规定,但我倾向于仅对符号方法名称使用中缀表示法,对字母数字方法名称使用点表示法.

I personally do not have any hard and fast rules for this, but I tend to use infix notation only with symbolic method names, and dot notation for alphanumeric ones.

中缀表示法使得以后修改代码很麻烦.以下是一些示例.

Infix notation makes it cumbersome to modify code later. Here are some examples.

想象一下你有这行代码:

Imagine you have this line of code:

xs filter { f } map { g }

假设在后面的某个时间点,您需要在末尾添加一个 toList.你是这样说的:

Suppose at some latter point in time you need to add a toList at end. You put it so:

xs filter { f } map { g } toList

这可能会导致分号推断问题.为避免这些问题,您要么在末尾添加分号,要么换行.在我看来,这两种选择都很丑陋.为了避免所有这些废话,我更喜欢使用 xs.filter(f).map(g).使用这种语法重构总是更容易.

This may cause semicolon inference issues. To avoid these issues, you either put a semicolon at end, or put a new line. Both options are ugly, in my opinion. To avoid all this nonsense, I prefer to go with xs.filter(f).map(g). It's always easier to refactor with this syntax.

另一个例子:假设我的代码中有以下内容:

Another example: Say I have the following in my code:

if(foo contains bar) { ..

说,我需要否定条件.如果我修改如下:

Say, I need to negate the condition. If I modify it as follows:

if(!foo contains bar) { ..

无赖.这被解析为 (!foo).contains(bar).不是我们想要的.

Bummer. This gets parsed as (!foo).contains(bar). Not what we wanted.

或者假设您需要另外添加一个新条件,然后修改它:

Or suppose you need to add a new condition in addition, and you modify it so:

if(foo contains bar && cond) { ..

另一个无赖.这被解析为 foo.contains(bar.&&(cond)).又不是我们想要的.

Another bummer. This gets parsed as foo.contains(bar.&&(cond)). Not what we wanted, again.

当然,您可以在周围添加一堆括号,但与点表示法相比,这会很丑陋且难以阅读/编辑.

Of course, you could add a bunch of parentheses around, but that would be ugly and hard to read/edit as compared with dot notation.

现在,我上面所说的所有内容也适用于符号方法名称.然而,符号方法与点语法一起使用时看起来不自然,因此我更喜欢它们的中缀语法.

Now, all of what I said above applies to symbolic method names too. However symbolic methods look unnatural when used with dot syntax, and so I prefer the infix syntax for them.

上述指南的一个例外:内部 DSL.它们通常是精心制作的,以免在以文档/示例中规定的方式编写时引起解析问题(通常使用中缀表示法).

One exception to the guideline above: Internal DSLs. They are usually crafted with care so as not to cause parsing issues when written in the manner prescribed in their documentation/examples (which usually uses infix notation).

这篇关于Scala - 中缀与点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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