Подтвердить что ты не робот

Scala Вспомогательные конструкторы

Ниже приведен класс Scala с конструкторами. Мои вопросы отмечены ****

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 definition must precede calling constructor 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)

}

Не могли бы вы ответить на мои вопросы в **** выше? Например, конструкторы не принимают параметры ошибки? Что это за ошибка компиляции?

4b9b3361

Ответ 1

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 = [email protected]

Первый this(3) - это делегирование первичного конструктора. Второй this(3) вызывает этот метод применения объекта, т.е. расширяется до this.apply(3). Обратите внимание на приведенный выше пример.

Ans 2:

= является необязательным в определениях конструктора, поскольку они действительно ничего не возвращают. Они имеют разную семантику из регулярных методов.

Ans 3:

private[this] называется модификатором объекта-частного доступа. Объект не может обращаться к другим объектам private[this], хотя оба они принадлежат одному классу. Таким образом, он более строгий, чем private. Соблюдайте приведенную ниже ошибку:

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:

То же, что и Ans 2.