Vikash Balasubramanian
Vikash Balasubramanian

Reputation: 3233

Calling the default constructor in scala

I have a class definition in scala

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

what is the difference between

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

How come 1. gives a compile time error? but calling this() inside "my constructor" doesn't give an error.

Upvotes: 0

Views: 460

Answers (1)

Gregor Raýman
Gregor Raýman

Reputation: 3081

The code you have provided does not compile. this() is not valid because there is no default constructor for the class A. this.p1 = somevalue is wrong, because there is not member p1.

Correctly it might look like this:

 class A(p1: Type1, p2: Type2) {
    def this(p1: Type1) {
      this(p1, someValueForP2)
    }
 }

or even better with default values:

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

Upvotes: 5

Related Questions