A possible issue with overriding vars in Scala 3


I’m working in the Scala plugin team in JetBrains and right now I’m implementing error highlighting for when a var from a superclass is overriden in a subclass. While doing this I noticed a weird difference between Scala 2 and 3. Consider this:

  trait Animal {
    var cat: String = ""

  class Cat extends Animal {
    override val cat: String = "cat"

In Scala 2, this code fails at compilation with

mutable variable cannot be overridden:
[error] def cat: String (defined in trait Animal)
[error]     override val cat: String = "cat"
[error]                  ^

but in Scala 3 compilation works.

Here’s a Scastie for it.

I have already seen this ticket and I can confirm it is fixed now, but the code above is a bit different - the var in the superclass is not abstract. You can modify the Scastie linked above to see how that changes how Scala 3 reacts. As far as I can tell, the only case where Scala 3 shows an error is when the field in the subclass is also a var: override var cat = "cat". error overriding variable cat in trait Animal of type String; [error] | variable cat of type String cannot override a mutable variable

But if the override is a val or a def, Scala 3 compiles it. Is this change in the behaviour done on purpose? It feels to me more like a forgotten detail. Can someone confirm either way?


Yup, it’s clearly a bug. Those overrides make no sense. Please file it as an issue. :wink:


Okay. Done.

Thank you for a quick answer :slight_smile: