Here are two method declaration:
def fun = "x"
def fun() = "x"
Since they both need no parameter and return a String, what's the difference besides invoking way?
Besides being right on the convention for no side effect for functions without parameters, there IS a difference between 'fun' and 'fun()' in Scala.
'fun' is called a 'parameterless' function, whereas 'fun()' is function with an 'empty parameter list'.
To make a long story short:
scala> def fun() = "x"
fun: ()java.lang.String
scala> fun
res0: java.lang.String = x
scala> fun()
res1: java.lang.String = x
scala> def fun = "y"
fun: java.lang.String
scala> fun
res2: java.lang.String = y
scala> fun()
<console>:9: error: not enough arguments for method apply: (index: Int)Char in class StringOps.
Unspecified value parameter index.
fun()
^
It's just a convention:
obj.fun //accessing like property with no side-effects
obj.fun() //ordinary method call, return value, but might also have side-effects
Prefer ()
version to emphasize that this is a method as opposed to simple property.
Note that this is just a convention, a way to document code, the compiler does not enforce the rules above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With