Why it is not possible to override mutable variable in scala?

前端 未结 5 1606
余生分开走
余生分开走 2020-12-30 04:27

Why it is not possible to override mutable variable in scala ?

class Abs(var name: String){
}

class AbsImpl(override var name: String) extends Abs(name){
}
         


        
5条回答
  •  粉色の甜心
    2020-12-30 05:10

    I believe that the intent was simply to set the value of the inherited var name. This can be achieved this way (without override var):

    class Abs(var name: String){
    }
    
    class AbsImpl(name: String) extends Abs(name){
    }
    

    The ambiguity arises from the local var name: String in AbsImpl that is named after the inherited var name: String from Abs. A similar code, less syntactically ambiguous but also less elegant would be:

    class Abs(var name: String){
    }
    
    class AbsImpl(name_value: String) extends Abs(name_value){
    }
    

提交回复
热议问题