Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between fun and fun() in Scala?

Tags:

methods

scala

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?

like image 284
Hesey Avatar asked Nov 22 '11 14:11

Hesey


2 Answers

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()
             ^
like image 139
ikarius Avatar answered Sep 30 '22 16:09

ikarius


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.

like image 22
Tomasz Nurkiewicz Avatar answered Sep 30 '22 18:09

Tomasz Nurkiewicz