Why introduce the lazy keyword?

View: New views
4 Messages — Rating Filter:   Alert me  

Why introduce the lazy keyword?

by rinswind-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hello everyone,
I am likely a future Scala fan - e.g. a current newby. I have been watching Scala for maybe 2 years
now and finally I'm taking the plunge and doing some serious exploration of the language. So...

As the title says: why introduce another keyword when there already exists a lazy mechanism for the
method parameters?

def foo(lazy: => Int)

Why not use the same mechanism for the lazy values?

class Foo {
  val lazy: => Int = {println ("evaluating the answer"); 42}
}

This might be more verbose and than using a "lazy" in front but to me it seems more "regular". Maybe
there is some fundamental difference between the "by name" parameters and the lazy vals that I am
missing?

Respectfully,
Todor

Re: Why introduce the lazy keyword?

by Florian Hars-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Todor Boev wrote:
> As the title says: why introduce another keyword when there already exists a lazy mechanism for the
> method parameters?
>
> def foo(lazy: => Int)

Because that is not lazy, that is by name:

scala> def f(byName: => Int) = { byName + byName }
f: (=> Int)Int

scala> f({println("Foo"); 2})
Foo
Foo
res20: Int = 4

scala> lazy val g = { println("Bar"); 2 }
Bar
g: Int = 2

scala> g + g
res21: Int = 4

- Florian

Re: Why introduce the lazy keyword?

by rinswind-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Florian Hars wrote:

> Todor Boev wrote:
>> As the title says: why introduce another keyword when there already
>> exists a lazy mechanism for the
>> method parameters?
>>
>> def foo(lazy: => Int)
>
> Because that is not lazy, that is by name:
>
> scala> def f(byName: => Int) = { byName + byName }
> f: (=> Int)Int
>
> scala> f({println("Foo"); 2})
> Foo
> Foo
> res20: Int = 4
>
> scala> lazy val g = { println("Bar"); 2 }
> Bar
> g: Int = 2
>
> scala> g + g
> res21: Int = 4
>
> - Florian
>

Argh! Just my brain trying to reduce the concept load. Should have tried this experiment myself. 10x :)

Re: Why introduce the lazy keyword?

by Paul Phillips-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Sun, Apr 19, 2009 at 05:57:20PM +0200, Florian Hars wrote:
> Because that is not lazy, that is by name:

See also:

  "add lazy parameters"
  https://lampsvn.epfl.ch/trac/scala/ticket/240

  "Syntax change for method and constructor arguments"
  https://lampsvn.epfl.ch/trac/scala/ticket/672

--
Paul Phillips      | We must respect the other fellow's religion, but only
Analgesic          | in the sense and to the extent that we respect his
Empiricist         | theory that his wife is beautiful and his children smart.
pp: i haul pills   |     -- H. L. Mencken