This page is no longer maintained — Please continue to the home page at www.scala-lang.org

local variables must be initialized...

3 replies
Martin S. Weber
Joined: 2008-12-23,
User offline. Last seen 42 years 45 weeks ago.

Why exactly? Consider:

> class A
> { var a : A = _ ; () }
> { var a : A = null ; () }

shouldn't the 2nd statement initialize `a` the same as the third after
all (for reference types)? 2nd is rejected, 3rd is allowed. It's not a
big pain, just use null instead of _ but IMO questions the sense of _
here.

-Martin

Alex Boisvert
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: local variables must be initialized...
Are you using Scala 2.7.3?

scala> class A { var a: A = _; () }
defined class A


On Fri, Apr 3, 2009 at 6:40 AM, Martin S. Weber <martin.weber@nist.gov> wrote:
Why exactly? Consider:

class A
{ var a : A = _ ; () }
{ var a : A = null ; () }

shouldn't the 2nd statement initialize `a` the same as the third after all (for reference types)? 2nd is rejected, 3rd is allowed. It's not a big pain, just use null instead of _ but IMO questions the sense of _ here.

-Martin

Florian Hars
Joined: 2008-12-18,
User offline. Last seen 42 years 45 weeks ago.
Re: local variables must be initialized...

Alex Boisvert schrieb:
> Are you using Scala 2.7.3?
>
> scala> class A { var a: A = _; () }
> defined class A

He had an additional newline:

scala> class A
defined class A

scala> { var a : A = _; () }
:6: error: local variables must be initialized
{ var a : A = _; () }
^
- Florian.

Martin S. Weber
Joined: 2008-12-23,
User offline. Last seen 42 years 45 weeks ago.
Re: local variables must be initialized...

Quoting Alex Boisvert :

> Are you using Scala 2.7.3?
>
> scala> class A { var a: A = _; () }
> defined class A

yes I'm using scala 2.7.3. I also wasn't talking about getter&setter
of a *class* but a *local variable*. See, statement 1 & 2 are on
separate lines, i.e. separated by an implicit semicolon. Or you can
look at:

scala> class A { def a : Unit = { var x: A = _ ; () } }
:4: error: local variables must be initialized
class A { def a : Unit = { var x: A = _ ; () } }
^

scala> class A { def a : Unit = { var x: A = null ; () } }
defined class A

-Martin

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland