2013-05-07 59 views
0

在Java中,我可以這樣做:的構造方法參數相同的名稱,atributes

class Point{ 
    int x, y; 
    public Point (int x, int y){ 
    this.x = x; 
    this.y = y; 
    } 
} 

我怎樣才能做到在斯卡拉同樣的事情(在構造函數參數和類屬性使用相同的名稱):

class Point(x: Int, y: Int){ 
    //Wrong code 
    def x = x; 
    def y = y; 
} 

編輯

我問這貝科使用下面的代碼不起作用

class Point(x: Int, y: Int) { 
    def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y) 
} 

但接下來一個工程:

class Point(px: Int, py: Int) { 
    def x = px 
    def y = py 
    def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y) 
} 
+2

在編輯中的第一個代碼片段中,使用'val'來聲明參數,並且您的代碼有效。 – xbonez 2013-05-07 04:26:45

回答

6

在Scala中,如果聲明爲varval,構造函數的參數將成爲該類的公共屬性。

scala> class Point(val x: Int, val y: Int){} 
defined class Point 

scala> val point = new Point(1,1) 
point: Point = [email protected] 

scala> point.x 
res0: Int = 1 

scala> point.y 
res1: Int = 1 

編輯來回答評論這個問題:「如果他們是私人領域,應該不是我的第一個代碼剪斷的編輯工作過之後?」

構造class Point(x: Int, y: Int)生成對象私有字段僅允許Point類的方法來訪問字段xyPoint類型的不其他對象。 that中的+方法是另一個對象,不允許使用此定義進行訪問。要在action中看到這個定義,請添加一個不會生成編譯錯誤的方法def xy:Int = x + y

要有xy到類訪問使用類私有字段,如下所示:

class Point(private val x: Int, private val y: Int) { 
    def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y) 
} 

現在他們是不是類以外訪問:

scala> val point = new Point(1,1) 
point: Point = [email protected] 

scala> point.x 
<console>:10: error: value x in class Point cannot be accessed in Point 
       point.x 
        ^
scala> point.y 
<console>:10: error: value y in class Point cannot be accessed in Point 
       point.y 

你可以通過使用scalac -Xprint:parser Point.scala來看到這一點。

+0

哦,謝謝!如果我不將它們設置爲val,那麼它們只是構造函數的參數,那麼是嗎?如果我想讓它們成爲私人屬性呢? – 2013-05-07 04:30:23

+1

參見http://www.scala-lang.org/node/539#comment-650瞭解如何使參數保密。 – xbonez 2013-05-07 04:32:16

+0

如果您不添加'var'或'val',則它們是類中構造函數和專用字段的參數。另請參閱http://ofps.oreilly.com/titles/9780596155957/BasicObjectOrientedProgramming.html – Brian 2013-05-07 04:36:28

0

你並不需要; Scala中所有你需要的類聲明中的「參數」。

+0

請看我的編輯 – 2013-05-07 04:24:42

+1

啊,看Brian的答案。使用'val'。 – 2013-05-07 04:25:40