Scala 中 构造函数,重载函数的执行顺序

在调试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 Int = if(height==0) 0 else contents(0).length
 5   }
 6 
 7 class UniformElement (ch :Char,
 8   override val 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 Int = if(height==0) 0 else contents(0).length
 5   }
 6 
 7   class UniformElement (ch:Char,
 8                         override val 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 中重载函数的执行要先于构造函数的执行。但是没搞明白为什么重载函数执行了两遍。

Scala 中 构造函数,重载函数的执行顺序