Scala Auxiliary constructors

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.

Tags:

Scala