In Java I'd normally initialize fields in a constructor in this way:
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
Is there a way to do the same in Scala for classes or objects? Like instead of
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
}
something like this:
class Complex(real: Double, imaginary: Double) {
def this.real = real
def this.imaginary = imaginary
}
Edit: whoops, I think I confused methods with fields here.
So far, nobody has directly answered your question. The Scala equivalent of the Java this operator is (surprise!) the Scala this operator. You did indeed confuse methods with fields in your example; your code would work as written if you replaced the defs with vals. However, as others have pointed out, you don't need this here.
Additionally, Scala allows you to define an 'alias' for this using the Explicitly Typed Self Reference syntax that Peter Schmitz demonstrated. The alias 'self' is frequently used, but any identifier is valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With