2011-12-09 141 views
12

以下是帶構造函數的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) 

} 

您能否回答我在****上面的問題?例如構造函數不會帶參數錯誤?這個編譯錯誤是什麼?

回答

11

答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)。觀察上面的例子。

答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)) 
           ^

答4:

同答2.

相關問題