Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are parenthesis required (or prohibited) on methods? [duplicate]

Tags:

scala

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!

like image 911
Void Main Avatar asked Mar 19 '12 02:03

Void Main


2 Answers

First, it's probably better to think of toLong and toString as being methods on the Int class than postfix operators. Integer literals are objects in Scala, and thus, have methods, two of which are toLong and toString. (Admittedly, the situation is slightly more complex with Int because 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:

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 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.

like image 156
dhg Avatar answered Nov 15 '22 10:11

dhg


See What is the rule for parenthesis in Scala method invocation? for detailed information.

Additionally Int.toLong is defined without parenthesis and therefore cannot be invoked with parenthesis. It is most likely defined without parenthesis because it does not have side effect (it's a convention).

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

like image 5
huynhjl Avatar answered Nov 15 '22 09:11

huynhjl