Why would a variable in Scala code mysteriously become null?

Posted by Alex R on Stack Overflow See other posts from Stack Overflow or by Alex R
Published on 2010-04-18T02:18:28Z Indexed on 2010/04/18 2:23 UTC
Read the original article Hit count: 315

I've isolated the problem down to this:

Predef.println("the value of argv1 here is " + argv(1));
var n: $ = undef;

n = argv(1);
Predef.println("the value of argv1 here is " + argv(1));
Predef.println("the value of n here is " + n);
Predef.println("the class of n here is " + n.getClass);

Here's the definition of $:

class $ {

    println("constructed a new $ of type: " + this.getClass);

    def value: $ = this;
    def toValue: Value = { new ConstStringValue(this.toString()) };

    def ->(sym: Symbol): $ = { println("looked up: " + sym); this }
    def ->(sym: $): $ = { println("looked up: " + sym); this }

    def update(sym: Symbol, any: Any) { 
        println("update called: " + sym + "=" + any);
    }

    def apply(sym: Symbol) = { this }
    def apply(obj: $) = { this }
    def apply() = { this }

    def +(o:$) = this.toValue.div(o.toValue)
    def *(o:$) = this.toValue.mul(o.toValue)
    def >(o:$) = this.toValue.gt(o.toValue)
    def <(o:$) = this.toValue.lt(o.toValue)
    def ++() = { this }
    def -=(o:$) = { this }

}

When run, the code prints:

the value of argv1 here is 10
the value of argv1 here is 10
the value of n here is null
java.lang.NullPointerException
        at test_1_php$.include(_tmp.scala:149)
        at php.script.main(php.scala:57)
        at test_1_php.main(_tmp.scala)
[...]

Why would n mysteriously lose its value (or fail to take one on)?

© Stack Overflow or respective owner

Related posts about scala

Related posts about programming-languages