在 Java 中,我通常以这种方式在构造函数中初始化字段:
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
有没有办法在 Scala 中对类或对象做同样的事情?喜欢而不是
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
}
像这样:
class Complex(real: Double, imaginary: Double) {
def this.real = real
def this.imaginary = imaginary
}
编辑:哎呀,我想我在这里把方法和字段搞混了。
最佳答案
到目前为止,还没有人直接回答您的问题。 Java this
运算符的 Scala 等价物是(惊喜!)Scala this
运算符。您确实在示例中将方法与字段混淆了;如果将 def
替换为 val
,您的代码将按编写的方式工作。但是,正如其他人指出的那样,您在这里不需要 this
。
此外,Scala 允许您使用显式类型自引用语法为 this
定义一个“别名”Peter Schmitz demonstrated .别名“self”经常使用,但任何标识符都是有效的。
关于java - Java 中 `this` 运算符的 Scala 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5450251/