(Not a) Scala compiler bug? (null pointer exception)
This code
v(2,1)
var m=Array[String]()
def v(f:Int,t:Int)=
{ var move= (10*f+t).toString
m :+ "21"
}
(run it as a scala script)
gives a null pointer exception when executing the m:+ "21" line.
This
var m=Array[String]()
def v(f:Int,t:Int)=
{ var move= (10*f+t).toString
m :+ "21"
}
v(2,1)
works. I think both should work and this is a compiler bug. Or am I mistaken?
Scala 2开发者_JAVA技巧.8.1, Windows XP
You are mistaken: you are attempting to access the variable m
before it has been initialized.
Note that just because the line with m
on it is before the "problematic" line (i.e. where the exception is thrown) does not necessarily mean that it is run first.
I made this class (which exhibits the same behaviour when you create it):
class OrderTest {
foo(1)
val l = List("one", "two")
def foo(i : Int) = println(l(i))
}
And then compiled with the -print option:
class OrderTest extends java.lang.Object with ScalaObject {
private[this] val l: List = _;
<stable> <accessor> def l(): List = OrderTest.this.l;
def foo(i: Int): Unit = scala.this.Predef.println(OrderTest.this.l().apply(i));
def this(): test.OrderTest = {
OrderTest.super.this();
OrderTest.this.foo(1);
OrderTest.this.l = immutable.this.List.apply(scala.this.Predef.wrapRefArray(Array[java.lang.String]{"one", "two"}.$asInstanceOf[Array[java.lang.Object]]()));
()
}
}
You can see quite clearly what is going on
精彩评论