I know this has been discussed on SO in other posts before and I understand the basic difference between the use of def
and val
. def
is used for defining a method and val
for an immutable reference. What I am trying to accomplish by asking this question is to understand if there is something more to def
. Can it be used interchangeably with a val
?
Recently I tried the following code and cannot convince myself if my present understanding of def
is sufficient:
scala> def i: Int = 3
i: Int
scala> i
res2: Int = 3
So I am curious, is this equivalent to val i = 3
?
Then I tried this:
scala> i()
<console>:9: error: Int does not take parameters
i()
I did this just to test my understanding of the semantics of def
. Now I want to know, when i
is a method, why Scala complains with "...does not take parameters"?
Next I tried the following:
scala> def i(): Int = 3
i: ()Int
scala> i()
res4: Int = 3
This time Scala seems to agree that i
is a method. So can I use def
in place of val
interchangeable to declare and initialize a variable?