How to override a mutable variable in Trait in scala?

后端 未结 4 1951
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 01:19

I\'d like override one mutable variable in Trait in constructor. But it will complain that \"overriding variable a in trait A of type Int; variable a cannot override a mutab

4条回答
  •  旧时难觅i
    2020-12-11 02:20

    Overriding is only for methods. It doesn't make sense to override a variable. What changes if you override a variable with another variable of the same type? If anything, the value and that can just be set anytime anyway, because it is a variable:

    trait A { 
      var a: Int = _ 
    }
    
    class B (a0: Int) extends A {
      a = a0
    }
    

    But that is propably not what you want. You may also just leave the getter and setter abstract:

    trait A {
      def a: Int
      def a_=(value: Int): Unit
    }
    
    class B(var a: Int)
    

    which is then equivalent to

    trait A {
      var a: Int
    }
    

提交回复
热议问题