gpt4 book ai didi

scala - 如何将 Scala 构造函数参数公开为公共(public)成员?

转载 作者:行者123 更新时间:2023-12-03 07:38:32 25 4
gpt4 key购买 nike

看这个例子:

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 类上定义一个 + 运算符方法。但这行不通因为在该方法中,xy 无法在 sourcePoint 局部变量上访问,因为它们是私有(private)的,所以我将示例更改为这个:

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。

感谢您的帮助和时间! :)

最佳答案

是的,有:

class Point(val x: Int, val y: Int)

关于scala - 如何将 Scala 构造函数参数公开为公共(public)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com