Following is a Scala class with constructors. My questions are marked with ****
class Constructors( a:Int, b:Int ) {
def this() =
{
this(4,5)
val s : String = "I want to dance after calling constructor"
//**** Constructors does not take parameters error? What is this compile error?
this(4,5)
}
def this(a:Int, b:Int, c:Int) =
{
//called constructor's definition must precede calling constructor's definition
this(5)
}
def this(d:Int)
// **** no equal to works? def this(d:Int) =
//that means you can have a constructor procedure and not a function
{
this()
}
//A private constructor
private def this(a:String) = this(1)
//**** What does this mean?
private[this] def this(a:Boolean) = this("true")
//Constructors does not return anything, not even Unit (read void)
def this(a:Double):Unit = this(10,20,30)
}
Could you please answer my questions in the **** above? For example Constructors does not take parameters error? What is this compile error?
Ans 1:
First
this(3)is a delegation to primary constructor. The secondthis(3)invokes this object’s apply method i.e. expands tothis.apply(3). Observe the above example.Ans 2:
=is optional in constructor definitions as they don’t really return anything. They have different semantics from regular methods.Ans 3:
private[this]is called object-private access modifier. An object cannot access other object’sprivate[this]fields even though they both belong to the same class. Thus it’s stricter thanprivate. Observe the error below:Ans 4:
Same as Ans 2.