Re: var vs def

Oliver Ruebenacker <[email protected]>
Newsgroups gmane.comp.lang.scala
Message-ID <CAA=X4OAvROWfEfWsXu2bdLKgt7FEc8B3u+ceEpUPQgwcynr8JA@mail.gmail.com>
     Hello,

  The right side of the = is evaluated once and the result is stored for a
var, but for a def, it is evaluated again every time you call it.

  Also, vars don't take parameters (not even an empty ()), but defs can.

  A def is called a method and it is subject to overloading and overriding.

  A var is a field if it is in top-level of a trait/class/object, otherwise
it is a local variable.

     Best, Oliver

On Sat, May 2, 2015 at 6:57 AM, scalanewbie <[email protected]> wrote:

> Hello All,
>
> I am a newbie to scala and getting in grasp with val and def.
>
> I noticed that I could write :
>
> scala> var greatWorld2 = println("great world")
>
> great world
>
> greatWorld2: Unit = ()
>
>
> AND
>
>
> scala> def greatWorld() = println("great world")
>
> greatWorld: ()Unit
>
>
> Can someone please help me understand the difference?
>
>
> I am aware that var is generally used to define variables and def is used
> to define functions.
>
>
> Now, keeping in mind that greatWorld2 is actually a variable and not a
> function, I am trying to print it, and I get:
>
>
> scala> greatWorld2
>
>
> OR, if I try calling it as a function, it throws an error e.g. below
> (which sounds ok as I did not declare this as a function, so was expecting
> this anyway).
>
>
> scala> greatWorld2()
>
> <console>:9: error: Unit does not take parameters
>
>               greatWorld2()
>
>
>
>  Long story short, difference between var and def , in terms of what the
> interpreter and or compiler is doing underneath will be very good to
> understand.
>
>
> Thanks Guys,
>
> S
>
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "scala-language" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Oliver Ruebenacker
Solutions Architect at Altisource Labs <http://www.altisourcelabs.com/>
Be always grateful, but never satisfied.

-- 
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.