scala / scala3

The Scala 3 compiler, also known as Dotty.
https://dotty.epfl.ch
Apache License 2.0
5.8k stars 1.05k forks source link

Confusing behaviour with abstract `var` and `override` #13019

Open oyvindberg opened 3 years ago

oyvindberg commented 3 years ago

Compiler version

3.0.0

Minimized code

// no `override` - fine
trait Ok1 { var i: Int }
class Ok1C extends Ok1 { var i: Int = 1 } 

// `override` of desugared `var` - fine
trait Ok2 {
  def i: Int
  def i_=(v: Int): Unit
}
class Ok2C extends Ok2 { override var i: Int = 1 }

// fails
trait NotOk {var i: Int}
class NotOkC extends NotOk { override var i: Int = 1 }

Output

error overriding variable i in trait NotOk of type Int;
  variable i of type Int cannot override a mutable variable

Expectation

override is used to implement abstract or re-implement concrete things, and guarantees their presence. In this case it seems impossible to use override to implement an abstract var.

The example compiles in scala 2

som-snytt commented 2 years ago

I submitted a quickie PR. override of abstract var is fine.

odersky commented 2 years ago

The fix in #13744 was not semantically correct.

When did Scala-2's behavior change? I tried with 2.13.5 and it also flags overrides of variables as errors.

smarter commented 2 years ago

When did Scala-2's behavior change?

In https://github.com/scala/scala/commit/9b59f5f9530d54c917479c6bf44aa3007ba0a2df which is part of 2.12.0. I tried it in both 2.12.0 and 2.13.5 and could get the following code to compile:

trait NotOk { var i: Int }
class NotOkC extends NotOk { override var i: Int = 1 }