user2848932
user2848932

Reputation: 786

write calculation code before this() function

could any one tell me why I could not write calculation code before this() function in scala class?

    //compile pass
     class A(a:Int) {
        def this() = {this(3)}
     }

     //compile error
     class A(a:Int) {
        def this() = {
          val tmp = 3 //or other complex calculations( error: 'this' expected but 'val' found.)
          this(tmp)
        }
     }

Upvotes: 0

Views: 73

Answers (1)

user1804599
user1804599

Reputation:

You cannot since you must call another constructor as the first thing in an auxiliary constructor. What you can do instead is use a block expression as argument:

class A(a:Int) {
  def this() = this({
    val tmp = 3
    tmp
  })
}

Upvotes: 1

Related Questions