Scala class members and constructor parameters name clash

前端 未结 4 1732
北荒
北荒 2021-02-05 07:30

Consider the following class written in Java:

class NonNegativeDouble {
    private final double value;
    public NonNegativeDouble(double value) {
        this         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 07:55

    @Daniel C. Sobral

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

    your code is right, but "constructor parameters are properties",this is not true.

    A post from the official site said,

    A parameter such as class Foo(x : Int) is turned into a field if it is referenced in one or more methods

    And Martin's reply confirms its truth:

    That's all true, but it should be treated as an implementation technique. That's why the spec is silent about it.

    So normally, we can still treat primary constructor parameters as normal method parameter, but when the parameters is referenced by any of the methods, the compiler will cleverly turn it into a private field.

    If any formal parameter preceded by the val, the compiler generates an getter definition automatically.if var, generates a setter additionally. see the language speification section 5.3.

    That's all about primary constructor parameters.

提交回复
热议问题