Possible Duplicate:
What is the rule for parenthesis in Scala method invocation?
I’m new to Scala, and I have some confusion with the () on 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 shall one use “()” after an operator? Is there any pattern in that?
Big Thanks!
First, it’s probably better to think of
toLongandtoStringas being methods on theIntclass than postfix operators. Integer literals are objects in Scala, and thus, have methods, two of which aretoLongandtoString. (Admittedly, the situation is slightly more complex withIntbecause of implicit conversions, etc, but this is a good way to think about it as a beginner.)So what are the rules for dropping parentheses? Scala syntax allows you to drop the
()if the method doesn’t take any arguments. However, if a method is defined without the parentheses, then they are not allowed at all:Finally, when do you drop parentheses and when do you keep them? By convention, in Scala we drop the parentheses for methods that have no side effects and keep them when there are side effects. Obviously this is just a style thing, but it gives an extra clue to readers about how your code works.