Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when I use def to define a field in Scala?

Tags:

scala

What exactly is the difference between:

scala> def foo = 5
foo: Int

and

scala> def foo() = 5
foo: ()Int

Seems that in both cases, I end up with a variable foo which I can refer to without parenthesis, always evaluating to 5.

like image 514
lindelof Avatar asked Aug 16 '10 14:08

lindelof


1 Answers

You're not defining a variable in either case. You're defining a method. The first method has no parameter lists, the second has one parameter list, which is empty. The first of these should be called like this

val x = foo 

while the second should be called like this

val x = foo()

However, the Scala compiler will let you call methods with one empty parameter list without the parentheses, so either form of call will work for the second method. Methods without parameter lists cannot be called with the parentheses

The preferred Scala style is to define and call no-argument methods which have side-effects with the parentheses. No-argument methods without side-effects should be defined and called without the parentheseses.

If you actually which to define a variable, the syntax is

val foo = 5
like image 200
Dave Griffith Avatar answered Oct 21 '22 05:10

Dave Griffith