在 Java 中,我可以这样做:
class Point{
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
}
如何在 Scala 中做同样的事情(在构造函数参数和类属性中使用相同的名称):
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)
}