Reputation: 786
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
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