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

问题描述

有没有一种最佳实践?我一直在阅读Odersky等人的 Scala书.似乎infix用于许多Collections API函数,而点则保留给程序员定义的函数.

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.

假设您有以下代码行:

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.

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

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-中缀与点表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:04