看看这个例子:
class Point(x: Double, y: Double){
override def toString = "x: " + x + ", y: " + y
def +(sourcePoint: Point) : Point = {
return new Point(x + sourcePoint.x, y + sourcePoint.y
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我想+在Point类上定义一个运算符方法.但是,这不会在方法,因为工作,x而y不能在访问sourcePoint局部变量,因为它们是私有的,所以我改变的例子为这样的:
class Point(_x: Double, _y: Double){
var x = _x
var y = _y
override def toString = "x: " + x + ", y: " + y
def +(sourcePoint: Point) : Point = {
return new Point(x + sourcePoint.x, y + sourcePoint.y)
}
}
Run Code Online (Sandbox Code Playgroud)
这显然有效,但是有一种更简单的方法来定义这些变量而不是从_x - > x和_y - > y.
感谢您的帮助和时间!:)
Nic*_*las 64
就在这里:
class Point(val x: Int, val y: Int)
Run Code Online (Sandbox Code Playgroud)
使用val有效,但参数变为final(常量).如果您希望能够重新分配您应该使用的值var.所以
class Point(var x: Int, var y: Int)
Run Code Online (Sandbox Code Playgroud)