如何将 Scala 构造函数参数公开为公共成员? [英] How do I expose Scala constructor arguments as public members?
本文介绍了如何将 Scala 构造函数参数公开为公共成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看看这个例子:
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
}
}
如您所见,我想在 Point 类上定义一个 +
运算符方法.但这行不通因为在那个方法中,x
和 y
不能在 sourcePoint
局部变量上访问,因为它们是私有的,所以我把例子改成了这个:
As you can see I want to define a +
operator method on the Point class. But this won't work
because in that method, x
and y
can't be accessed on the sourcePoint
local variable since they are private, so I changed the example into this:
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)
}
}
这显然有效,但是有没有更简单的方法来定义这些变量,而不是从 _x -> x 和 _y -> y 开始.
That obviously worked, however is there an easier way to define these variables instead of going from _x -> x and _y -> y.
感谢您的帮助和时间!:)
Thanks for help and time! :)
推荐答案
是的,有:
class Point(val x: Int, val y: Int)
这篇关于如何将 Scala 构造函数参数公开为公共成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文