在scala中调用默认构造函数

时间:2015-06-17 09:39:19

标签: scala

我在scala中有一个类定义

class A(p1: Type1,p2: Type2){
    def this(p1: Type1){  //my constructor
       this()
       this.p1 = somevalue
    }
}

之间有什么区别
1. val a:A = new A //Is this same as A()??
2. val a:A = new A(v1,v2)

怎么来1.给出编译时错误?但在“我的构造函数”中调用this()不会产生错误。

1 个答案:

答案 0 :(得分:5)

您提供的代码无法编译。 this()无效,因为类A没有默认构造函数。 this.p1 = somevalue错误,因为没有成员p1

正确地看起来像这样:

 class A(p1: Type1, p2: Type2) {
    def this(p1: Type1) {
      this(p1, someValueForP2)
    }
 }
使用默认值

甚至更好:

class A(p1: Type1 = defaultForP1, p2: Type2 = defaultForP2)