2011-12-09 7 views
12

Poniżej znajduje się klasa Scala z konstruktorami. Moje pytania są oznaczone symbolem ****Scala Pomocniczy konstruktorzy

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) 

} 

Czy możesz odpowiedzieć na moje pytania w powyższym ****? Na przykład Konstruktory nie przyjmuje błędu parametrów? Co to za błąd kompilacji?

Odpowiedz

11

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] 

Pierwszy this(3) jest delegacja do pierwotnego konstruktora. Drugi numer this(3) wywołuje metodę stosowania tego obiektu, tj. Rozszerza się do this.apply(3). Obserwuj powyższy przykład.

Ans 2:

= jest opcjonalne w definicji konstruktora, ponieważ tak naprawdę nie zwraca niczego. Mają inną semantykę niż zwykłe metody.

Ans 3:

private[this] nazywany jest obiektem prywatnym dostęp modyfikator. Obiekt nie może uzyskać dostępu do pól obiektu innego obiektu, nawet jeśli obie należą do tej samej klasy. Dlatego jest bardziej rygorystyczny niż private. Przestrzegać poniższy błąd:

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:

samo jak Ans 2.

Powiązane problemy