14

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 mutable variable". Why the scala do not allow me do that ? And any best practise for this ? Thanks

trait A{
  var a:Int = _
}

class B(override var a:Int) extends A
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • 1
    Did you simplify your true case to make the question? As pointed out by many answers, it's pretty useless to override a var with another of the same name and type. – pagoda_5b May 08 '13 at 08:29

4 Answers4

18

You cannot override it (for reasons that don't reveal themselves to me right now, except, that vars can be modified anyway so why override them), but you can leave the declared variable uninitialised and delegate the latter to B:

trait A {
  var a: Int
}

class B(var a: Int) extends A
Malte Schwerhoff
  • 12,684
  • 4
  • 41
  • 71
  • I think.. am learning myself. It's to do with details around how it autogens setters and getters & efficiency in the compiler. But yeah am not sure why you would override it other than to deliberately duplicate code. – Shaun Ryan Apr 21 '20 at 07:40
7

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
}
Martin Ring
  • 5,404
  • 24
  • 47
1

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
Vikas Pandya
  • 1,998
  • 1
  • 15
  • 32
1

try use val instead of var and use override. It work when A is abstract class, Like this:

abstract class A{
  val a:Int = 0
}

class B extends A{
override val a:Int=1
}
xmcx
  • 283
  • 3
  • 18