« Return to Thread: difference between def/val assignment

Re: difference between def/val assignment

by Chris Twiner :: Rate this Message:

Reply to Author | View in Thread

hiya,

def declares a method, each subsequent access makes the expression run
again. In this line:

        a.value = "new value"

you get a new Data, set its value and discard it.  The only "trick" is
that, as in this case, you can define one without parameters, but it
will always re-evaluate.

I hope the rest makes sense given that.

cheers,
Chris

On Wed, Jul 8, 2009 at 1:35 PM, Christoph Drießen<ced@...> wrote:

> Hi all,
>
> running the following code yields
>
> null
> null
> null
> new value
>
> class Data {
>    var value: String = _
> }
>
> object DataTest {
>    def main(args: Array[String]) {
>        def a = new Data
>        val b = new Data
>
>        println(a.value)
>        println(b.value)
>
>        a.value = "new value"
>        b.value = "new value"
>
>        println(a.value)
>        println(b.value)
>    }
> }
>
> Can anyone explain the difference between def and val in this situation?
> Playing around with both I cannot find any difference between 'a' and 'b',
> they are both the same class. But 'a' must be something different. What
> exactly is it then?
>
> Cheers,
> Christoph
>

 « Return to Thread: difference between def/val assignment