- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
App, DelayedInit and NPE
Wed, 2011-05-18, 16:46
It took me quite a while until I discovered the cause of an NPE:
object Test extends App {
val outer = "a"
override def main(args: Array[String]):Unit = {
val inner = "b"
println(outer)
println(inner)
}
}
>scala Test.app
>null
>b
the website[1] says: "Scala’s new App trait stores all initialization
sequences in an internal buffer and executes them when the object’s
main method is called."
When in this case means after? And why after the main method?
best wishes,
ido
[1]http://www.scala-lang.org/node/9483
Wed, 2011-05-18, 17:17
#2
Re: App, DelayedInit and NPE
> I have no idea for your problem, but... What is the point to use App if
> you write a main method ?
>
I started with App then discovered that I have to do
scalac Test.scala && scala Test
so now I just do scala Test.scala (not as written above scala
Test.app)
best,
ido
Wed, 2011-05-18, 17:27
#3
Re: App, DelayedInit and NPE
On Wed, May 18, 2011 at 5:46 PM, ido wrote:
> the website[1] says: "Scala’s new App trait stores all initialization
> sequences in an internal buffer and executes them when the object’s
> main method is called."
>
> When in this case means after?
There is no 'after' in this case ?!?
DelayedInit allows a class to defer running the initialization code of
a class to a later point of time. What happens here, particularly, is
that the implementation of App.main executes all the initialization
code of the class which extends App (instead of the initialization
code being run when the object is instantiated as usual). In your
example you override `main` and therefore override this behavior with
your own which never calls the initialization code. Thus, outer is
never initialized.
Wed, 2011-05-18, 17:37
#4
Re: App, DelayedInit and NPE
On Wed, May 18, 2011 at 8:52 AM, Francois <fanf42@gmail.com> wrote:
Tangentially, perhaps App.main should be made final to avoid such surprises?
alex
On 18/05/2011 17:46, ido wrote:
It took me quite a while until I discovered the cause of an NPE:
object Test extends App {
val outer = "a"
override def main(args: Array[String]):Unit = {
val inner = "b"
println(outer)
println(inner)
}
}
scala Test.app
null
b
I have no idea for your problem, but... What is the point to use App if you write a main method ?
Tangentially, perhaps App.main should be made final to avoid such surprises?
alex
On 18/05/2011 17:46, ido wrote:
> It took me quite a while until I discovered the cause of an NPE:
>
> object Test extends App {
> val outer = "a"
> override def main(args: Array[String]):Unit = {
> val inner = "b"
> println(outer)
> println(inner)
> }
> }
>
>> scala Test.app
>> null
>> b
I have no idea for your problem, but... What is the point to use App if
you write a main method ?