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

前端 未结 5 1610
余生分开走
余生分开走 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:21

    If you could override a var with a var, then the overriding member could have a narrower type. (That's how overriding is defined.)

    You could then assign a value of a wider type and then read it expecting the narrower type, and fail.

    Illustration of the setter involved:

    scala> class A ; class B extends A
    defined class A
    defined class B
    
    scala> abstract class C { var x: A } ; class D extends C { var x: B = _ }
    :13: error: class D needs to be abstract, since variable x in class C of type A is not defined
    (Note that an abstract var requires a setter in addition to the getter)
           abstract class C { var x: A } ; class D extends C { var x: B = _ }
                                                 ^
    
    scala> abstract class C { var x: A }
    defined class C
    
    scala> class D extends C { var x: B = _ ; def x_=(a: A) = ??? }
    defined class D
    

提交回复
热议问题