scala中主构造器并没有明确的定义过程,主构造器是通过class参数列表和类的body中的代码实现的,如下:
class PConstructor(x:Int,y:Int) { override def toString: String = x + "," + y println("hello world") } object MyTest extends App { val a = new PConstructor(1,2) println(a) }其最终的输出结果是
hello world
1,2
将类中的方法都去掉就可以得到class中的body了,在加上参数列表就可以将其主构造器提取出来,对上述代码而言就类似下面的代码(当然这是不合法的):
PConstructor (x:Int