Re: var vs def

martin odersky <[email protected]>
Newsgroups gmane.comp.lang.scala
Message-ID <CAENVNkaBmLmtrkfOcG0xJ+VEo2yS1sAB4JpxO-3Zf_Azv+GDAg@mail.gmail.com>
On Sat, May 2, 2015 at 12:57 PM, 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
>
You are probably surprised that you see no output. That's because
greatWorld2 returns a unit value (after all, its type is Unit) and the
REPL does not print unit values. It could print () but it assumes that
you executed the expression for its side effects only.

Hope this helps

 - Martin

>
> 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.



-- 
Martin Odersky
EPFL

-- 
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.