Scala辅助构造函数

Pra*_*one 14 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'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)

}
Run Code Online (Sandbox Code Playgroud)

你可以在上面的****中回答我的问题吗?例如,构造函数不带参数错误?什么是编译错误?

mis*_*tor 13

答案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
Run Code Online (Sandbox Code Playgroud)

首先this(3)是对主要构造函数的委派.第二个this(3)调用此对象的apply方法,即扩展为this.apply(3).请注意上面的例子.

答案2:

=在构造函数定义中是可选的,因为它们实际上不返回任何内容.它们与常规方法有不同的语义.

答案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))
                                 ^
Run Code Online (Sandbox Code Playgroud)

答案4:

与Ans 2相同.