Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Scala equivalent of the `this` operator in Java?

Tags:

java

this

scala

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.

like image 410
zumjinger Avatar asked Dec 07 '25 04:12

zumjinger


1 Answers

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.

like image 178
Aaron Novstrup Avatar answered Dec 08 '25 16:12

Aaron Novstrup