I am experiencing some strange thing related with case classes and override protected val
.
Let's say trait T
have a protected def
(or val
).
trait T {
protected def s: String
def print(): Unit = println(s)
}
I can override this method def s
with val s
. There's no problem.
class A(override val s: String) extends T
OK. It compiles. But this makes s
public since there is no protected keyword.
class B extends T {
override protected val s: String = "Show me the money"
}
OK. It compiles. (s
of class B
is protected)
class C(override protected val s: String) extends T
OK. It compiles. (s
of class C
is protected)
Let's do these with case class
.
case class D(override val s: String) extends T
OK. It compiles. (although s
of class D
is public)
case class E() extends T {
override protected val s: String = "Show me the money"
}
OK. It compiles. (s
of class E
is protected)
case class F(protected val s: String) extends T
OK. It compiles. (s
of class F
is protected, and also s
is overriden as it was not concrete in trait T
. It was abstract, so override
keyword is not necessary.)
case class G(override protected val s: String) extends T
Here, compile error appears.
error: value s$1 overrides nothing
Basically, class F
and class G
are the same. class F
overrides s
and s
is protected. This can be shown by that F("Something").print()
will indeed print Something
.
override protected val
can be used in case class as class E
shows. It did not make errors in defining normal class C
.
However, only defining class G
results in a compile error.
Why does this thing happen?
I'm using Scala 2.10.3
This bug will be fixed in Scala 2.11.0-M8
https://issues.scala-lang.org/browse/SI-8132
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With