开发者

When to use " " ( space ) and when to use . ( dot ) when invoking methods in Scala?

I've seen Scala using both interchangeably, but I don't know when to use one or the other.

Is there a convention?

For instance these are equivalent

"hello" toString 

and

"hello".toString()

And they can even be mixed

"hello".toStri开发者_JAVA百科ng() length 

What's the convention?


The space convention is generally used when the method functions like an operator (+, *, etc.); the dot convention is used when it functions more like, well, a method call.

(I know that explanation is kind of vague, but there's not really a hard and fast rule for the usage.)


To expand on the comment from Yardena, there is an Scala unofficial style guide. It has some suggestions on when to use the dot notation and when to drop the dot and the parenthesis and usually provides a brief rationale for the recommendation, that you may or may not agree with, but at least that's a starting point.

For instance name toList may behave differently depending on what's on the next line.

Personally, I would write hello.toString.length with the assumption that all calls are side-effect free (so I drop the parenthesis) and then I have to keep the dot for it to compile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜