When are parentheses necessary (or forbidden) for methods?

Possible duplicate:
What is the rule for parentheses in a Scala method call?

I'm new to Scala and I have some confusion with () for the postfix operator

I was told that toLong and toString are postfix operators for any integer, so I tried the following operations:

scala> 7 toString res18: java.lang.String = 7 scala> 7.toString() res19: java.lang.String = 7 scala> 7.toString res20: java.lang.String = 7 scala> 7.toLong res21: Long = 7 scala> 7.toLong() <console>:8: error: Long does not take parameters 7.toLong() ^ 

So, when do you need to use "()" after the statement? Is there a pattern in this?

Many thanks!

+4
source share
2 answers

First, it is better to think of toLong and toString as methods of the Int class, rather than postfix operators. Integer literals are objects in Scala and therefore have methods, two of which are toLong and toString . (Admittedly, the situation is a bit more complicated with Int due to implicit conversions, etc., but this is a good way to think of it as a newbie.)

So what are the rules for releasing parentheses? Scala syntax allows you to drop () if the method does not accept any arguments. However, if the method is defined without parentheses, then they are not allowed at all:

 class A() { def stuff() = "stuff" def things = "things" } val a = new A() a.stuff // fine a.stuff() // fine a.things // fine a.things() // error! 

Finally, when do you drop parentheses and when do you save them? By convention, in Scala we drop parentheses for methods that do not have side effects and retain them when there are side effects. Obviously, this is just a style, but it gives an additional key to readers about how your code works.

+12
source

For more details, see What is the parenthesis rule in a Scala method call? .

Additionally, Int.toLong defined without parentheses and therefore cannot be called using parentheses. Most likely, it is defined without parentheses, since it has no side effect (this is an agreement).

Since toString() comes from Java, for interoperability it was defined using brackets and therefore can be called with or without brackets.

+5
source

Source: https://habr.com/ru/post/1402160/


All Articles