Scala class members and constructor parameters name clash

前端 未结 4 1739
北荒
北荒 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

    In the case of case classes it should be:

    case class NonNegativeDouble(private val initValue: Double) {
      val value = Math.abs(initValue)
      def copy(value: Double = this.value) = NonNegativeDouble(value)
    }
    

    The implementation of copy is required to prevent the sintesized version of the compiler that will bind the initValue argument.

    I expect that the compiler is smart enough to not retain the «extra space» for the initValue. I haven't verified this behaviour.

提交回复
热议问题