在調試scala在線開發教程(http://www.imobilebbs.com/wordpress/archives/4911)的過程中看到了以下代碼,但是這段代碼無論怎么調試都無法成功。
1 abstract class Element{ 2 def contents:Array[String] 3 val height:Int = contents.length 4 val width:Int = if(height==0) 0 else contents(0).length 5 } 6 7 class UniformElement (ch :Char, 8 override val width:Int, 9 override val height:Int 10 ) extends Element{ 11 private val line=ch.toString * width 12 def contents = Array.fill(height)(line) 13 } 14 15 val ue = new UniformElement('x',2,3) 16 println(ue.contents)
錯誤如下:
Exception in thread "main" java.lang.NullPointerException
分析原因如下:
以上代碼的12行 12 def contents = Array.fill(height)(line) 引用了第11行定義的變量line: private val line=ch.toString * width. 按理說在執行12行的時候,line應該已經被初始化了。而實際上在執行12行的時候,line 依然是null. 所以導致了上面的異常。
可能的原因就是Scala 中重載函數的執行要先於構造函數的執行 。 為了驗證想法,對代碼做了以下改動:
1 abstract class Element{ 2 def contents:Array[String] 3 val height:Int = contents.length 4 val width:Int = if(height==0) 0 else contents(0).length 5 } 6 7 class UniformElement (ch:Char, 8 override val width:Int, 9 override val height:Int 10 ) extends Element{ 11 val line = ch.toString * width 12 println("Initialize done") 13 def contents:Array[String] = { 14 println("override done") 15 Array.fill(height)(ch.toString * width) 16 } 17 //def cons:Array[String] = Array.fill(height)(line) 18 } 19 20 val ue = new UniformElement('x',2,3)
運行結果如下:事實說明Scala 中重載函數的執行要先於構造函數的執行。但是沒搞明白為什么重載函數執行了兩遍。