如何将 Scala 构造函数参数公开为公共成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9864111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I expose Scala constructor arguments as public members?
提问by user1285925
Look at this example:
看这个例子:
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
}
}
As you can see I want to define a +operator method on the Point class. But this won't work
because in that method, xand ycan't be accessed on the sourcePointlocal variable since they are private, so I changed the example into this:
如您所见,我想+在 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)
}
}
That obviously worked, however is there an easier way to define these variables instead of going from _x -> x and _y -> y.
这显然有效,但是有没有更简单的方法来定义这些变量,而不是从 _x -> x 和 _y -> y 开始。
Thanks for help and time! :)
感谢您的帮助和时间!:)
回答by Nicolas
Yes, there is:
就在这里:
class Point(val x: Int, val y: Int)
回答by yerlilbilgin
using valis valid but then the parameter becomes final (constant).
If you want to be able to reassign the value you should use varinstead. So
usingval是有效的,但随后参数变为最终(常量)。如果您希望能够重新分配您应该使用的值var。所以
class Point(var x: Int, var y: Int)

