views:

79

answers:

1

Hi.

Consider the following class written in Java:

class NonNegativeDouble {
    private final double value;
    public NonNegativeDouble(double value) {
        this.value = Math.abs(value);
    }
    public double getValue() { return value; }
}

It defines a final field called value that is initialized in the constructor, by taking its parameter called alike and applying a function to it.

I want to write something similar to it in Scala. At first, I tried:

class NonNegativeDouble(value: Double) {
  def value = Math.abs(value)
}

But the compiler complains: error: overloaded method value needs result type

Obviously the compiler thinks that the expression value inside the expression Math.abs(value) refers to the method being defined. Therefore, the method being defined is recursive, so I need to state its return type. So, the code I wrote does not do what I expected it to do: I wanted value inside Math.abs(value) to refer to the constructor parameter value, and not to the method being defined. It is as if the compiler implicitly added a this. to Math.abs(this.value).

Adding val or var (or private ... variants) to the constructor parameter doesn't seem to help.

So, my question is: can I define a property with the same name as a constructor parameter, but maybe a different value? If so, how? If not, why?

Thanks!

+4  A: 

No, you can't. In Scala, constructor parameters are properties, so it makes no sense to redefine them.

The solution, naturally, is to use another name:

class NonNegativeDouble(initValue: Double) {
  val value = Math.abs(initValue)
}

Used like this, initValue won't be part of the instances created. However, if you use it in a def or a pattern matching declaration, then it becomes a part of ever instance of the class.

Daniel
A constructor isn't made a property unless it's a case class or annotated with val or var. It is available for use anywhere inside the class definition though.
Geoff Reedy
@Daniel: Is there any kind of naming convention of the constructor parameters in such cases?
Bruno Reis
@Bruno - There are several naming conventions; I personally like the one where a 0 is appended to the name, since that zero implies a starting point, and it's brief. (Underscores are sometimes prepended or appended, but I personally feel that there are plenty underscores lying around already.)
Rex Kerr
@Geoff It is a private property.
Daniel