How to override a mutable variable in Trait in scala?

后端 未结 4 1947
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  庸人自扰
    2020-12-11 02:16

    Note exactly sure what you would want to achieve with an attempt to "override" a "var" which as others have mentioned you can change anyways.

    Among many other guesses, one is that you would want something like self type members? where self type annotation allows you to access members of a mixin trait or class, and Scala compiler ensures that all the dependencies are correctly wired? If so, something like following will work.

    trait B{
    var a:Int = _
    

    }

    trait A{self:B=> var b= a}
    class C extends A with B
    

提交回复
热议问题