PrathameshMone
PrathameshMone

Reputation: 405

Scala Auxiliary constructors

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?

Upvotes: 14

Views: 5114

Answers (2)

Adriaan
Adriaan

Reputation: 13

Related to question 2 is:

Scala Auxilliary Constructor behavior

This is causing the error, the lack of (default) parameters for int b and int c throws called constructor's definition must precede calling constructor's definition

Upvotes: 0

missingfaktor
missingfaktor

Reputation: 92016

Ans 1:

scala> class Boo(a: Int) {
     |   def this() = { this(3); println("lol"); this(3) }
     |   def apply(n: Int) = { println("apply with " + n) }
     | }
defined class Boo

scala> new Boo()
lol
apply with 3
res0: Boo = Boo@fdd15b

First this(3) is a delegation to primary constructor. The second this(3) invokes this object's apply method i.e. expands to this.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's private[this] fields even though they both belong to the same class. Thus it's stricter than private. Observe the error below:

scala> class Boo(private val a: Int, private[this] val b: Int) {
     |   def foo() {
     |     println((this.a, this.b))
     |   }
     | }
defined class Boo

scala> new Boo(2, 3).foo()
(2,3)

scala> class Boo(private val a: Int, private[this] val b: Int) {
     |   def foo(that: Boo) {
     |     println((this.a, this.b))
     |     println((that.a, that.b))
     |   }
     | }
<console>:17: error: value b is not a member of Boo
           println((that.a, that.b))
                                 ^

Ans 4:

Same as Ans 2.

Upvotes: 13

Related Questions