在scala中调用默认构造函数

Vik*_*h B 0 scala

我在scala中有一个类定义

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

有什么区别

1. val a:A = new A //Is this same as A()??
2. val a:A = new A(v1,v2)
Run Code Online (Sandbox Code Playgroud)

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

Gre*_*man 5

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

正确地看起来像这样:

 class A(p1: Type1, p2: Type2) {
    def this(p1: Type1) {
      this(p1, someValueForP2)
    }
 }
Run Code Online (Sandbox Code Playgroud)

甚至更好的默认值:

class A(p1: Type1 = defaultForP1, p2: Type2 = defaultForP2)
Run Code Online (Sandbox Code Playgroud)