Scala class members and constructor parameters name clash

前端 未结 4 1736
北荒
北荒 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 08:05

    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 every instance of the class.

提交回复
热议问题